diff --git a/libs/remix-analyzer/.eslintrc b/libs/remix-analyzer/.eslintrc index 71cbe7d7cd..cc6cabcbcd 100644 --- a/libs/remix-analyzer/.eslintrc +++ b/libs/remix-analyzer/.eslintrc @@ -2,7 +2,9 @@ "extends": "../../.eslintrc", "rules": { "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-unused-vars": "off" + "@typescript-eslint/no-unused-vars": "off", + "no-unused-vars": "off", + "dot-notation": "off" }, "ignorePatterns": ["!**/*"] } diff --git a/libs/remix-analyzer/src/index.ts b/libs/remix-analyzer/src/index.ts index 2639abeec9..38fadbab93 100644 --- a/libs/remix-analyzer/src/index.ts +++ b/libs/remix-analyzer/src/index.ts @@ -1 +1 @@ -export { default as CodeAnalysis} from './solidity-analyzer' +export { default as CodeAnalysis } from './solidity-analyzer' diff --git a/libs/remix-analyzer/src/solidity-analyzer/index.ts b/libs/remix-analyzer/src/solidity-analyzer/index.ts index b2ebd62d77..da6b5bb35e 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/index.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/index.ts @@ -9,7 +9,6 @@ type ModuleObj = { } export default class staticAnalysisRunner { - /** * Run analysis (Used by IDE) * @param compilationResult contract compilation result @@ -18,9 +17,9 @@ export default class staticAnalysisRunner { */ run (compilationResult: CompilationResult, toRun: number[], callback: ((reports: AnalysisReport[]) => void)): void { const modules: ModuleObj[] = toRun.map((i) => { - const module = this.modules()[i] - const m = new module() - return { 'name': m.name, 'mod': m } + const Module = this.modules()[i] + const m = new Module() + return { name: m.name, mod: m } }) this.runWithModuleList(compilationResult, modules, callback) } @@ -36,21 +35,21 @@ export default class staticAnalysisRunner { // Also provide convenience analysis via the AST walker. const walker = new AstWalker() for (const k in compilationResult.sources) { - walker.walkFull(compilationResult.sources[k].ast, + walker.walkFull(compilationResult.sources[k].ast, (node: any) => { - modules.map((item: ModuleObj) => { - if (item.mod.visit !== undefined) { - try { - item.mod.visit(node) - } catch (e) { - reports.push({ - name: item.name, report: [{ warning: 'INTERNAL ERROR in module ' + item.name + ' ' + e.message, error: e.stack }] - }) + modules.map((item: ModuleObj) => { + if (item.mod.visit !== undefined) { + try { + item.mod.visit(node) + } catch (e) { + reports.push({ + name: item.name, report: [{ warning: 'INTERNAL ERROR in module ' + item.name + ' ' + e.message, error: e.stack }] + }) + } } - } - }) - return true - } + }) + return true + } ) } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/abstractAstView.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/abstractAstView.ts index e6a7ac20af..0febc41dc1 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/abstractAstView.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/abstractAstView.ts @@ -1,9 +1,13 @@ -import { getStateVariableDeclarationsFromContractNode, getInheritsFromName, getContractName, - getFunctionOrModifierDefinitionParameterPart, getType, getDeclaredVariableName, - getFunctionDefinitionReturnParameterPart, getCompilerVersion } from './staticAnalysisCommon' +import { + getStateVariableDeclarationsFromContractNode, getInheritsFromName, getContractName, + getFunctionOrModifierDefinitionParameterPart, getType, getDeclaredVariableName, + getFunctionDefinitionReturnParameterPart, getCompilerVersion +} from './staticAnalysisCommon' import { AstWalker } from '@remix-project/remix-astwalker' -import { FunctionDefinitionAstNode, ParameterListAstNode, ModifierDefinitionAstNode, ContractHLAst, VariableDeclarationAstNode, - FunctionHLAst, ReportObj, ReportFunction, VisitFunction, ModifierHLAst, CompilationResult } from '../../types' +import { + FunctionDefinitionAstNode, ParameterListAstNode, ModifierDefinitionAstNode, ContractHLAst, VariableDeclarationAstNode, + FunctionHLAst, ReportObj, ReportFunction, VisitFunction, ModifierHLAst, CompilationResult +} from '../../types' type WrapFunction = ((contracts: ContractHLAst[], isSameName: boolean, version: string) => ReportObj[]) @@ -23,7 +27,7 @@ export default class abstractAstView { */ multipleContractsWithSameName = false -/** + /** * Builds a higher level AST view. I creates a list with each contract as an object in it. * Example contractsOut: * @@ -48,9 +52,10 @@ export default class abstractAstView { * @contractsOut {list} return list for high level AST view * @return {ASTNode -> void} returns a function that can be used as visit function for static analysis modules, to build up a higher level AST view for further analysis. */ + // eslint-disable-next-line camelcase build_visit (relevantNodeFilter: ((node:any) => boolean)): VisitFunction { return (node: any) => { - if (node.nodeType === "ContractDefinition") { + if (node.nodeType === 'ContractDefinition') { this.setCurrentContract({ node: node, functions: [], @@ -59,11 +64,11 @@ export default class abstractAstView { inheritsFrom: [], stateVariables: getStateVariableDeclarationsFromContractNode(node) }) - } else if (node.nodeType === "InheritanceSpecifier") { + } else if (node.nodeType === 'InheritanceSpecifier') { const currentContract: ContractHLAst = this.getCurrentContract() const inheritsFromName: string = getInheritsFromName(node) currentContract.inheritsFrom.push(inheritsFromName) - } else if (node.nodeType === "FunctionDefinition") { + } else if (node.nodeType === 'FunctionDefinition') { this.setCurrentFunction({ node: node, relevantNodes: [], @@ -78,14 +83,14 @@ export default class abstractAstView { this.getCurrentFunction().relevantNodes.push(item.node) } }) - } else if (node.nodeType === "ModifierDefinition") { + } else if (node.nodeType === 'ModifierDefinition') { this.setCurrentModifier({ node: node, relevantNodes: [], localVariables: this.getLocalVariables(node), parameters: this.getLocalParameters(node) }) - } else if (node.nodeType === "ModifierInvocation") { + } else if (node.nodeType === 'ModifierInvocation') { if (!this.isFunctionNotModifier) throw new Error('abstractAstView.js: Found modifier invocation outside of function scope.') this.getCurrentFunction().modifierInvocations.push(node) } else if (relevantNodeFilter(node)) { @@ -102,6 +107,7 @@ export default class abstractAstView { } } + // eslint-disable-next-line camelcase build_report (wrap: WrapFunction): ReportFunction { // eslint-disable-next-line @typescript-eslint/no-unused-vars return (compilationResult: CompilationResult) => { @@ -176,7 +182,7 @@ export default class abstractAstView { private getLocalVariables (funcNode: ParameterListAstNode): VariableDeclarationAstNode[] { const locals: VariableDeclarationAstNode[] = [] new AstWalker().walkFull(funcNode, (node: any) => { - if (node.nodeType === "VariableDeclaration") locals.push(node) + if (node.nodeType === 'VariableDeclaration') locals.push(node) return true }) return locals diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/assignAndCompare.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/assignAndCompare.ts index 44525ec2e9..1abca17307 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/assignAndCompare.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/assignAndCompare.ts @@ -1,13 +1,15 @@ -import { default as category } from './categories' +import category from './categories' import { isSubScopeWithTopLevelUnAssignedBinOp, getUnAssignedTopLevelBinOps } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, BlockAstNode, IfStatementAstNode, - WhileStatementAstNode, ForStatementAstNode, CompilationResult, ExpressionStatementAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import { + AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, BlockAstNode, IfStatementAstNode, + WhileStatementAstNode, ForStatementAstNode, CompilationResult, ExpressionStatementAstNode, SupportedVersion +} from './../../types' export default class assignAndCompare implements AnalyzerModule { warningNodes: ExpressionStatementAstNode[] = [] - name = `Result not used: ` - description = `The result of an operation not used` + name = 'Result not used: ' + description = 'The result of an operation not used' category: ModuleCategory = category.MISC algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/blockBlockhash.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/blockBlockhash.ts index 142c04ed73..714e7f62dd 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/blockBlockhash.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/blockBlockhash.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' +import category from './categories' import { isBlockBlockHashAccess } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion } from './../../types' export default class blockBlockhash implements AnalyzerModule { warningNodes: FunctionCallAstNode[] = [] - name = `Block hash: ` - description = `Can be influenced by miners` + name = 'Block hash: ' + description = 'Can be influenced by miners' category: ModuleCategory = category.SECURITY algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -30,4 +30,3 @@ export default class blockBlockhash implements AnalyzerModule { }) } } - diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/blockTimestamp.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/blockTimestamp.ts index a71c650105..be78b7e90b 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/blockTimestamp.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/blockTimestamp.ts @@ -1,23 +1,25 @@ -import { default as category } from './categories' +import category from './categories' import { isNowAccess, isBlockTimestampAccess, getCompilerVersion } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, IdentifierAstNode, - MemberAccessAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import { + AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, IdentifierAstNode, + MemberAccessAstNode, SupportedVersion +} from './../../types' export default class blockTimestamp implements AnalyzerModule { warningNowNodes: IdentifierAstNode[] = [] warningblockTimestampNodes: MemberAccessAstNode[] = [] - name = `Block timestamp: ` - description = `Can be influenced by miners` + name = 'Block timestamp: ' + description = 'Can be influenced by miners' category: ModuleCategory = category.SECURITY algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { start: '0.4.12' } - visit (node: IdentifierAstNode | MemberAccessAstNode ): void { - if (node.nodeType === "Identifier" && isNowAccess(node)) this.warningNowNodes.push(node) - else if (node.nodeType === "MemberAccess" && isBlockTimestampAccess(node)) this.warningblockTimestampNodes.push(node) + visit (node: IdentifierAstNode | MemberAccessAstNode): void { + if (node.nodeType === 'Identifier' && isNowAccess(node)) this.warningNowNodes.push(node) + else if (node.nodeType === 'MemberAccess' && isBlockTimestampAccess(node)) this.warningblockTimestampNodes.push(node) } // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/categories.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/categories.ts index 478c355693..855d691b8c 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/categories.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/categories.ts @@ -1,6 +1,6 @@ export default { - SECURITY: {displayName: 'Security', id: 'SEC'}, - GAS: {displayName: 'Gas & Economy', id: 'GAS'}, - MISC: {displayName: 'Miscellaneous', id: 'MISC'}, - ERC: {displayName: 'ERC', id: 'ERC'} + SECURITY: { displayName: 'Security', id: 'SEC' }, + GAS: { displayName: 'Gas & Economy', id: 'GAS' }, + MISC: { displayName: 'Miscellaneous', id: 'MISC' }, + ERC: { displayName: 'ERC', id: 'ERC' } } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/checksEffectsInteraction.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/checksEffectsInteraction.ts index 41bf539ce9..e0cf9adac6 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/checksEffectsInteraction.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/checksEffectsInteraction.ts @@ -1,16 +1,20 @@ -import { default as category } from './categories' -import { isInteraction, isEffect, isLocalCallGraphRelevantNode, getFullQuallyfiedFuncDefinitionIdent, - isWriteOnStateVariable, isStorageVariableDeclaration, getFullQualifiedFunctionCallIdent, getCompilerVersion } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' +import category from './categories' +import { + isInteraction, isEffect, isLocalCallGraphRelevantNode, getFullQuallyfiedFuncDefinitionIdent, + isWriteOnStateVariable, isStorageVariableDeclaration, getFullQualifiedFunctionCallIdent, getCompilerVersion +} from './staticAnalysisCommon' +import algorithm from './algorithmCategories' import { buildGlobalFuncCallGraph, resolveCallGraphSymbol, analyseCallGraph } from './functionCallGraph' -import AbstractAst from './abstractAstView' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VariableDeclarationAstNode, - FunctionHLAst, ContractCallGraph, Context, FunctionCallAstNode, AssignmentAstNode, UnaryOperationAstNode, - InlineAssemblyAstNode, ReportFunction, VisitFunction, FunctionCallGraph, SupportedVersion } from './../../types' +import AbstractAst from './abstractAstView' +import { + AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VariableDeclarationAstNode, + FunctionHLAst, ContractCallGraph, Context, FunctionCallAstNode, AssignmentAstNode, UnaryOperationAstNode, + InlineAssemblyAstNode, ReportFunction, VisitFunction, FunctionCallGraph, SupportedVersion +} from './../../types' export default class checksEffectsInteraction implements AnalyzerModule { - name = `Check-effects-interaction: ` - description = `Potential reentrancy bugs` + name = 'Check-effects-interaction: ' + description = 'Potential reentrancy bugs' category: ModuleCategory = category.SECURITY algorithm: ModuleAlgorithm = algorithm.HEURISTIC version: SupportedVersion = { @@ -20,11 +24,11 @@ export default class checksEffectsInteraction implements AnalyzerModule { abstractAst: AbstractAst = new AbstractAst() visit: VisitFunction = this.abstractAst.build_visit((node: FunctionCallAstNode | AssignmentAstNode | UnaryOperationAstNode | InlineAssemblyAstNode) => ( - node.nodeType === 'FunctionCall' && (isInteraction(node) || isLocalCallGraphRelevantNode(node))) || + node.nodeType === 'FunctionCall' && (isInteraction(node) || isLocalCallGraphRelevantNode(node))) || ((node.nodeType === 'Assignment' || node.nodeType === 'UnaryOperation' || node.nodeType === 'InlineAssembly') && isEffect(node))) report: ReportFunction = this.abstractAst.build_report(this._report.bind(this)) - + private _report (contracts: ContractHLAst[], multipleContractsWithSameName: boolean, version: string): ReportObj[] { const warnings: ReportObj[] = [] const hasModifiers: boolean = contracts.some((item) => item.modifiers.length > 0) @@ -32,16 +36,16 @@ export default class checksEffectsInteraction implements AnalyzerModule { contracts.forEach((contract) => { contract.functions.forEach((func) => { func['changesState'] = this.checkIfChangesState( - getFullQuallyfiedFuncDefinitionIdent( - contract.node, - func.node, - func.parameters - ), - this.getContext( - callGraph, - contract, - func) - ) + getFullQuallyfiedFuncDefinitionIdent( + contract.node, + func.node, + func.parameters + ), + this.getContext( + callGraph, + contract, + func) + ) }) contract.functions.forEach((func: FunctionHLAst) => { if (this.isPotentialVulnerableFunction(func, this.getContext(callGraph, contract, func))) { @@ -50,7 +54,7 @@ export default class checksEffectsInteraction implements AnalyzerModule { comments += (multipleContractsWithSameName) ? 'Note: Import aliases are currently not supported by this static analysis.' : '' warnings.push({ warning: `Potential violation of Checks-Effects-Interaction pattern in ${funcName}: Could potentially lead to re-entrancy vulnerability. ${comments}`, - location: func.node['src'], + location: func.node.src, more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#re-entrancy` }) } @@ -92,4 +96,3 @@ export default class checksEffectsInteraction implements AnalyzerModule { return analyseCallGraph(context.callGraph, startFuncName, context, (node: any, context: Context) => isWriteOnStateVariable(node, context.stateVariables)) } } - diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/constantFunctions.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/constantFunctions.ts index ac6fac6690..abbdb91807 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/constantFunctions.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/constantFunctions.ts @@ -1,17 +1,21 @@ -import { default as category } from './categories' -import { isLowLevelCall, isTransfer, isExternalDirectCall, isEffect, isLocalCallGraphRelevantNode, isSelfdestructCall, - isDeleteUnaryOperation, isPayableFunction, isConstructor, getFullQuallyfiedFuncDefinitionIdent, hasFunctionBody, - isConstantFunction, isWriteOnStateVariable, isStorageVariableDeclaration, isCallToNonConstLocalFunction, - getFullQualifiedFunctionCallIdent} from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' +import category from './categories' +import { + isLowLevelCall, isTransfer, isExternalDirectCall, isEffect, isLocalCallGraphRelevantNode, isSelfdestructCall, + isDeleteUnaryOperation, isPayableFunction, isConstructor, getFullQuallyfiedFuncDefinitionIdent, hasFunctionBody, + isConstantFunction, isWriteOnStateVariable, isStorageVariableDeclaration, isCallToNonConstLocalFunction, + getFullQualifiedFunctionCallIdent +} from './staticAnalysisCommon' +import algorithm from './algorithmCategories' import { buildGlobalFuncCallGraph, resolveCallGraphSymbol, analyseCallGraph } from './functionCallGraph' -import AbstractAst from './abstractAstView' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractCallGraph, Context, ContractHLAst, - FunctionHLAst, VariableDeclarationAstNode, FunctionCallGraph, FunctionCallAstNode, VisitFunction, ReportFunction, SupportedVersion} from './../../types' +import AbstractAst from './abstractAstView' +import { + AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractCallGraph, Context, ContractHLAst, + FunctionHLAst, VariableDeclarationAstNode, FunctionCallGraph, FunctionCallAstNode, VisitFunction, ReportFunction, SupportedVersion +} from './../../types' export default class constantFunctions implements AnalyzerModule { - name = `Constant/View/Pure functions: ` - description = `Potentially constant/view/pure functions` + name = 'Constant/View/Pure functions: ' + description = 'Potentially constant/view/pure functions' category: ModuleCategory = category.MISC algorithm: ModuleAlgorithm = algorithm.HEURISTIC version: SupportedVersion = { @@ -26,8 +30,8 @@ export default class constantFunctions implements AnalyzerModule { isExternalDirectCall(node) || isEffect(node) || isLocalCallGraphRelevantNode(node) || - node.nodeType === "InlineAssembly" || - node.nodeType === "NewExpression" || + node.nodeType === 'InlineAssembly' || + node.nodeType === 'NewExpression' || isSelfdestructCall(node) || isDeleteUnaryOperation(node) ) @@ -46,17 +50,17 @@ export default class constantFunctions implements AnalyzerModule { func['potentiallyshouldBeConst'] = false } else { func['potentiallyshouldBeConst'] = this.checkIfShouldBeConstant( - getFullQuallyfiedFuncDefinitionIdent( - contract.node, - func.node, - func.parameters - ), - this.getContext( - callGraph, - contract, - func - ) - ) + getFullQuallyfiedFuncDefinitionIdent( + contract.node, + func.node, + func.parameters + ), + this.getContext( + callGraph, + contract, + func + ) + ) } }) contract.functions.filter((func: FunctionHLAst) => hasFunctionBody(func.node)).forEach((func: FunctionHLAst) => { @@ -67,13 +71,13 @@ export default class constantFunctions implements AnalyzerModule { if (func['potentiallyshouldBeConst']) { warnings.push({ warning: `${funcName} : Potentially should be constant/view/pure but is not. ${comments}`, - location: func.node['src'], + location: func.node.src, more: `https://solidity.readthedocs.io/en/${version}/contracts.html#view-functions` }) } else { warnings.push({ warning: `${funcName} : Is constant but potentially should not be. ${comments}`, - location: func.node['src'], + location: func.node.src, more: `https://solidity.readthedocs.io/en/${version}/contracts.html#view-functions` }) } @@ -101,8 +105,8 @@ export default class constantFunctions implements AnalyzerModule { isTransfer(node) || this.isCallOnNonConstExternalInterfaceFunction(node, context) || isCallToNonConstLocalFunction(node) || - node.nodeType === "InlineAssembly" || - node.nodeType === "NewExpression" || + node.nodeType === 'InlineAssembly' || + node.nodeType === 'NewExpression' || isSelfdestructCall(node) || isDeleteUnaryOperation(node) } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/deleteDynamicArrays.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/deleteDynamicArrays.ts index b5c9831909..dd814b382e 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/deleteDynamicArrays.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/deleteDynamicArrays.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' +import category from './categories' import { isDeleteOfDynamicArray, getCompilerVersion } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion } from './../../types' export default class deleteDynamicArrays implements AnalyzerModule { rel: UnaryOperationAstNode[] = [] - name = `Delete dynamic array: ` - description = `Use require/assert to ensure complete deletion` + name = 'Delete dynamic array: ' + description = 'Use require/assert to ensure complete deletion' category: ModuleCategory = category.GAS algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -22,7 +22,7 @@ export default class deleteDynamicArrays implements AnalyzerModule { const version = getCompilerVersion(compilationResults.contracts) return this.rel.map((node) => { return { - warning: `The "delete" operation when applied to a dynamically sized array in Solidity generates code to delete each of the elements contained. If the array is large, this operation can surpass the block gas limit and raise an OOG exception. Also nested dynamically sized objects can produce the same results.`, + warning: 'The "delete" operation when applied to a dynamically sized array in Solidity generates code to delete each of the elements contained. If the array is large, this operation can surpass the block gas limit and raise an OOG exception. Also nested dynamically sized objects can produce the same results.', location: node.src, more: `https://solidity.readthedocs.io/en/${version}/types.html#delete` } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/deleteFromDynamicArray.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/deleteFromDynamicArray.ts index c1db4da71b..714da95c65 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/deleteFromDynamicArray.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/deleteFromDynamicArray.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' -import { default as algorithm } from './algorithmCategories' +import category from './categories' +import algorithm from './algorithmCategories' import { isDeleteFromDynamicArray, isMappingIndexAccess } from './staticAnalysisCommon' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion} from './../../types' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, UnaryOperationAstNode, SupportedVersion } from './../../types' export default class deleteFromDynamicArray implements AnalyzerModule { relevantNodes: UnaryOperationAstNode[] = [] - name = `Delete from dynamic array: ` - description = `'delete' leaves a gap in array` + name = 'Delete from dynamic array: ' + description = '\'delete\' leaves a gap in array' category: ModuleCategory = category.MISC algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -21,7 +21,7 @@ export default class deleteFromDynamicArray implements AnalyzerModule { report (compilationResults: CompilationResult): ReportObj[] { return this.relevantNodes.map((node) => { return { - warning: `Using "delete" on an array leaves a gap. The length of the array remains the same. If you want to remove the empty position you need to shift items manually and update the "length" property.`, + warning: 'Using "delete" on an array leaves a gap. The length of the array remains the same. If you want to remove the empty position you need to shift items manually and update the "length" property.', location: node.src, more: 'https://github.com/miguelmota/solidity-idiosyncrasies#examples' } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/erc20Decimals.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/erc20Decimals.ts index 24af05f215..c9264920c7 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/erc20Decimals.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/erc20Decimals.ts @@ -1,13 +1,15 @@ -import { default as category } from './categories' +import category from './categories' import { getFunctionDefinitionName, helpers, getDeclaredVariableName, getDeclaredVariableType } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import AbstractAst from './abstractAstView' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, VisitFunction, ReportFunction, ContractHLAst, - FunctionHLAst, VariableDeclarationAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import AbstractAst from './abstractAstView' +import { + AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, VisitFunction, ReportFunction, ContractHLAst, + FunctionHLAst, VariableDeclarationAstNode, SupportedVersion +} from './../../types' export default class erc20Decimals implements AnalyzerModule { - name = `ERC20: ` - description = `'decimals' should be 'uint8'` + name = 'ERC20: ' + description = '\'decimals\' should be \'uint8\'' category: ModuleCategory = category.ERC algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -34,11 +36,11 @@ export default class erc20Decimals implements AnalyzerModule { (f.returns.length === 0 || f.returns.length > 1) || (f.returns.length === 1 && (f.returns[0].type !== 'uint8' || f.node.visibility !== 'public')) ) - ) + ) if (decimalsVar.length > 0) { for (const node of decimalsVar) { warnings.push({ - warning: `ERC20 contract's "decimals" variable should be "uint8" type`, + warning: 'ERC20 contract\'s "decimals" variable should be "uint8" type', location: node.src, more: 'https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals' }) @@ -46,7 +48,7 @@ export default class erc20Decimals implements AnalyzerModule { } else if (decimalsFun.length > 0) { for (const fn of decimalsFun) { warnings.push({ - warning: `ERC20 contract's "decimals" function should have "uint8" as return type`, + warning: 'ERC20 contract\'s "decimals" function should have "uint8" as return type', location: fn.node.src, more: 'https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#decimals' }) @@ -66,4 +68,3 @@ export default class erc20Decimals implements AnalyzerModule { funSignatures.includes('allowance(address,address)') } } - diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/etherTransferInLoop.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/etherTransferInLoop.ts index 3af43fa2be..a8f8ae1d55 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/etherTransferInLoop.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/etherTransferInLoop.ts @@ -1,40 +1,43 @@ -import { default as category } from './categories' -import { default as algorithm } from './algorithmCategories' +import category from './categories' +import algorithm from './algorithmCategories' import { isLoop, isTransfer, getCompilerVersion } from './staticAnalysisCommon' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode, - WhileStatementAstNode, ExpressionStatementAstNode, SupportedVersion} from './../../types' +import { + AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode, + WhileStatementAstNode, ExpressionStatementAstNode, SupportedVersion +} from './../../types' export default class etherTransferInLoop implements AnalyzerModule { relevantNodes: ExpressionStatementAstNode[] = [] - name = `Ether transfer in loop: ` - description = `Transferring Ether in a for/while/do-while loop` + name = 'Ether transfer in loop: ' + description = 'Transferring Ether in a for/while/do-while loop' category: ModuleCategory = category.GAS algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { start: '0.4.12' } - + visit (node: ForStatementAstNode | WhileStatementAstNode): void { - let transferNodes: ExpressionStatementAstNode[] = [] - if(isLoop(node)) { - if(node.body && node.body.nodeType === 'Block') - transferNodes = node.body.statements.filter(child => ( child.nodeType === 'ExpressionStatement' && - child.expression.nodeType === 'FunctionCall' && isTransfer(child.expression.expression))) - // When loop body is described without braces - else if(node.body && node.body.nodeType === 'ExpressionStatement' && node.body.expression.nodeType === 'FunctionCall' && isTransfer(node.body.expression.expression)) - transferNodes.push(node.body) - if (transferNodes.length > 0) { - this.relevantNodes.push(...transferNodes) - } + let transferNodes: ExpressionStatementAstNode[] = [] + if (isLoop(node)) { + if (node.body && node.body.nodeType === 'Block') { + transferNodes = node.body.statements.filter(child => + (child.nodeType === 'ExpressionStatement' && + child.expression.nodeType === 'FunctionCall' && + isTransfer(child.expression.expression))) + } else if (node.body && node.body.nodeType === 'ExpressionStatement' && node.body.expression.nodeType === 'FunctionCall' && isTransfer(node.body.expression.expression)) { transferNodes.push(node.body) } + // When loop body is described without braces + if (transferNodes.length > 0) { + this.relevantNodes.push(...transferNodes) } + } } - + // eslint-disable-next-line @typescript-eslint/no-unused-vars report (compilationResults: CompilationResult): ReportObj[] { const version = getCompilerVersion(compilationResults.contracts) return this.relevantNodes.map((node) => { return { - warning: `Ether payout should not be done in a loop: Due to the block gas limit, transactions can only consume a certain amount of gas. The number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. If required then make sure that number of iterations are low and you trust each address involved.`, + warning: 'Ether payout should not be done in a loop: Due to the block gas limit, transactions can only consume a certain amount of gas. The number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. If required then make sure that number of iterations are low and you trust each address involved.', location: node.src, more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#gas-limit-and-loops` } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/forLoopIteratesOverDynamicArray.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/forLoopIteratesOverDynamicArray.ts index f2f0c0dfcb..ff85469cf2 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/forLoopIteratesOverDynamicArray.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/forLoopIteratesOverDynamicArray.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' -import { default as algorithm } from './algorithmCategories' +import category from './categories' +import algorithm from './algorithmCategories' import { isDynamicArrayLengthAccess, getCompilerVersion } from './staticAnalysisCommon' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode, SupportedVersion} from './../../types' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, ForStatementAstNode, SupportedVersion } from './../../types' export default class forLoopIteratesOverDynamicArray implements AnalyzerModule { relevantNodes: ForStatementAstNode[] = [] - name = `For loop over dynamic array: ` - description = `Iterations depend on dynamic array's size` + name = 'For loop over dynamic array: ' + description = 'Iterations depend on dynamic array\'s size' category: ModuleCategory = category.GAS algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -14,21 +14,21 @@ export default class forLoopIteratesOverDynamicArray implements AnalyzerModule { } visit (node: ForStatementAstNode): void { - const { condition } = node - // Check if condition is `i < array.length - 1` - if ((condition && condition.nodeType === "BinaryOperation" && condition.rightExpression.nodeType === "BinaryOperation" && isDynamicArrayLengthAccess(condition.rightExpression.leftExpression)) || + const { condition } = node + // Check if condition is `i < array.length - 1` + if ((condition && condition.nodeType === 'BinaryOperation' && condition.rightExpression.nodeType === 'BinaryOperation' && isDynamicArrayLengthAccess(condition.rightExpression.leftExpression)) || // or condition is `i < array.length` - (condition && condition.nodeType === "BinaryOperation" && isDynamicArrayLengthAccess(condition.rightExpression))) { - this.relevantNodes.push(node) - } + (condition && condition.nodeType === 'BinaryOperation' && isDynamicArrayLengthAccess(condition.rightExpression))) { + this.relevantNodes.push(node) + } } - + // eslint-disable-next-line @typescript-eslint/no-unused-vars report (compilationResults: CompilationResult): ReportObj[] { const version = getCompilerVersion(compilationResults.contracts) return this.relevantNodes.map((node) => { return { - warning: `Loops that do not have a fixed number of iterations, for example, loops that depend on storage values, have to be used carefully. Due to the block gas limit, transactions can only consume a certain amount of gas. The number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. \n Additionally, using unbounded loops incurs in a lot of avoidable gas costs. Carefully test how many items at maximum you can pass to such functions to make it successful.`, + warning: 'Loops that do not have a fixed number of iterations, for example, loops that depend on storage values, have to be used carefully. Due to the block gas limit, transactions can only consume a certain amount of gas. The number of iterations in a loop can grow beyond the block gas limit which can cause the complete contract to be stalled at a certain point. \n Additionally, using unbounded loops incurs in a lot of avoidable gas costs. Carefully test how many items at maximum you can pass to such functions to make it successful.', location: node.src, more: `https://solidity.readthedocs.io/en/${version}/security-considerations.html#gas-limit-and-loops` } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/functionCallGraph.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/functionCallGraph.ts index ae7b77a660..a83666d68b 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/functionCallGraph.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/functionCallGraph.ts @@ -1,14 +1,16 @@ 'use strict' -import { FunctionHLAst, ContractHLAst, FunctionCallGraph, ContractCallGraph, Context, FunctionCallAstNode } from "../../types" -import { isLocalCallGraphRelevantNode, isExternalDirectCall, getFullQualifiedFunctionCallIdent, - getFullQuallyfiedFuncDefinitionIdent, getContractName } from './staticAnalysisCommon' +import { FunctionHLAst, ContractHLAst, FunctionCallGraph, ContractCallGraph, Context, FunctionCallAstNode } from '../../types' +import { + isLocalCallGraphRelevantNode, isExternalDirectCall, getFullQualifiedFunctionCallIdent, + getFullQuallyfiedFuncDefinitionIdent, getContractName +} from './staticAnalysisCommon' type filterNodesFunction = (node: FunctionCallAstNode) => boolean type NodeIdentFunction = (node: FunctionCallAstNode) => string type FunDefIdentFunction = (node: FunctionHLAst) => string -function buildLocalFuncCallGraphInternal (functions: FunctionHLAst[], nodeFilter: filterNodesFunction , extractNodeIdent: NodeIdentFunction, extractFuncDefIdent: FunDefIdentFunction): Record { +function buildLocalFuncCallGraphInternal (functions: FunctionHLAst[], nodeFilter: filterNodesFunction, extractNodeIdent: NodeIdentFunction, extractFuncDefIdent: FunDefIdentFunction): Record { const callGraph: Record = {} functions.forEach((func: FunctionHLAst) => { const calls: string[] = func.relevantNodes @@ -76,7 +78,7 @@ function analyseCallGraphInternal (callGraph: Record, visited[funcName] = true return combinator(current.node.relevantNodes.reduce((acc, val) => combinator(acc, nodeCheck(val, context)), false), - current.calls.reduce((acc, val) => combinator(acc, analyseCallGraphInternal(callGraph, val, context, combinator, nodeCheck, visited)), false)) + current.calls.reduce((acc, val) => combinator(acc, analyseCallGraphInternal(callGraph, val, context, combinator, nodeCheck, visited)), false)) } export function resolveCallGraphSymbol (callGraph: Record, funcName: string): FunctionCallGraph | undefined { @@ -92,7 +94,7 @@ function resolveCallGraphSymbolInternal (callGraph: Record[] = this.warningNodes.map(node => { - let signature: string; - if(node.nodeType === 'FunctionDefinition'){ + const methodsWithSignature: Record[] = this.warningNodes.map(node => { + let signature: string + if (node.nodeType === 'FunctionDefinition') { const functionName: string = getFunctionDefinitionName(node) signature = helpers.buildAbiSignature(functionName, getMethodParamsSplittedTypeDesc(node, compilationResults.contracts)) - } - else - signature = node.name + '()' - + } else { signature = node.name + '()' } + return { name: node.name, src: node.src, @@ -42,8 +41,8 @@ export default class gasCosts implements AnalyzerModule { for (const contractName in compilationResults.contracts[filename]) { const contract: CompiledContract = compilationResults.contracts[filename][contractName] const methodGas: Record | undefined = this.checkMethodGas(contract, method.signature) - if(methodGas && methodGas.isInfinite) { - if(methodGas.isFallback) { + if (methodGas && methodGas.isInfinite) { + if (methodGas.isFallback) { report.push({ warning: `Fallback function of contract ${contractName} requires too much gas (${methodGas.msg}). If the fallback function requires more than 2300 gas, the contract cannot receive Ether.`, @@ -57,7 +56,7 @@ export default class gasCosts implements AnalyzerModule { (this includes clearing or copying arrays in storage)`, location: method.src }) - } + } } else continue } } @@ -65,17 +64,17 @@ export default class gasCosts implements AnalyzerModule { return report } - private checkMethodGas(contract: CompiledContract, methodSignature: string): Record | undefined { - if(contract.evm && contract.evm.gasEstimates && contract.evm.gasEstimates.external) { - if(methodSignature === '()') { + private checkMethodGas (contract: CompiledContract, methodSignature: string): Record | undefined { + if (contract.evm && contract.evm.gasEstimates && contract.evm.gasEstimates.external) { + if (methodSignature === '()') { const fallback: string = contract.evm.gasEstimates.external[''] - if (fallback !== undefined && (fallback === null || parseInt(fallback) >= 2100 || fallback === 'infinite')) { - return { - isInfinite: true, - isFallback: true, - msg: fallback - } - } + if (fallback !== undefined && (fallback === null || parseInt(fallback) >= 2100 || fallback === 'infinite')) { + return { + isInfinite: true, + isFallback: true, + msg: fallback + } + } } else { const gas: string = contract.evm.gasEstimates.external[methodSignature] const gasString: string = gas === null ? 'unknown or not constant' : 'is ' + gas @@ -85,8 +84,8 @@ export default class gasCosts implements AnalyzerModule { isFallback: false, msg: gasString } - } + } } } - } + } } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/guardConditions.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/guardConditions.ts index bd1c7e079c..b2c67fbef4 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/guardConditions.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/guardConditions.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' +import category from './categories' import { isRequireCall, isAssertCall, getCompilerVersion } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, FunctionCallAstNode, SupportedVersion } from './../../types' export default class guardConditions implements AnalyzerModule { guards: FunctionCallAstNode[] = [] - name = `Guard conditions: ` - description = `Ensure appropriate use of require/assert` + name = 'Guard conditions: ' + description = 'Ensure appropriate use of require/assert' category: ModuleCategory = category.MISC algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -22,7 +22,7 @@ export default class guardConditions implements AnalyzerModule { const version = getCompilerVersion(compilationResults.contracts) return this.guards.map((node) => { return { - warning: `Use "assert(x)" if you never ever want x to be false, not in any circumstance (apart from a bug in your code). Use "require(x)" if x can be false, due to e.g. invalid input or a failing external component.`, + warning: 'Use "assert(x)" if you never ever want x to be false, not in any circumstance (apart from a bug in your code). Use "require(x)" if x can be false, due to e.g. invalid input or a failing external component.', location: node.src, more: `https://solidity.readthedocs.io/en/${version}/control-structures.html#error-handling-assert-require-revert-and-exceptions` } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/index.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/index.ts index 35e189932e..d76b94539a 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/index.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/index.ts @@ -18,4 +18,4 @@ export { default as stringBytesLength } from './stringBytesLength' export { default as intDivisionTruncate } from './intDivisionTruncate' export { default as etherTransferInLoop } from './etherTransferInLoop' export { default as deleteFromDynamicArray } from './deleteFromDynamicArray' -export { default as forLoopIteratesOverDynamicArray } from './forLoopIteratesOverDynamicArray' \ No newline at end of file +export { default as forLoopIteratesOverDynamicArray } from './forLoopIteratesOverDynamicArray' diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/inlineAssembly.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/inlineAssembly.ts index 52c78f89a5..851fc2f10d 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/inlineAssembly.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/inlineAssembly.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, InlineAssemblyAstNode, SupportedVersion} from './../../types' +import category from './categories' +import algorithm from './algorithmCategories' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, InlineAssemblyAstNode, SupportedVersion } from './../../types' import { getCompilerVersion } from './staticAnalysisCommon' export default class inlineAssembly implements AnalyzerModule { inlineAssNodes: InlineAssemblyAstNode[] = [] - name = `Inline assembly: ` - description = `Inline assembly used` + name = 'Inline assembly: ' + description = 'Inline assembly used' category: ModuleCategory = category.SECURITY algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -14,7 +14,7 @@ export default class inlineAssembly implements AnalyzerModule { } visit (node: InlineAssemblyAstNode): void { - if(node.nodeType === 'InlineAssembly') this.inlineAssNodes.push(node) + if (node.nodeType === 'InlineAssembly') this.inlineAssNodes.push(node) } // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/intDivisionTruncate.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/intDivisionTruncate.ts index e324aaa03b..b54053202b 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/intDivisionTruncate.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/intDivisionTruncate.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' +import category from './categories' import { isIntDivision } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, BinaryOperationAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, BinaryOperationAstNode, SupportedVersion } from './../../types' export default class intDivisionTruncate implements AnalyzerModule { warningNodes: BinaryOperationAstNode[] = [] - name = `Data truncated: ` - description = `Division on int/uint values truncates the result` + name = 'Data truncated: ' + description = 'Division on int/uint values truncates the result' category: ModuleCategory = category.MISC algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/lowLevelCalls.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/lowLevelCalls.ts index dba4c7221f..39ee3faa2d 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/lowLevelCalls.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/lowLevelCalls.ts @@ -1,7 +1,7 @@ -import { default as category } from './categories' +import category from './categories' import { isLLCall, isLLDelegatecall, isLLCallcode, isLLCall04, isLLDelegatecall04, isLLSend04, isLLSend, lowLevelCallTypes, getCompilerVersion } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion } from './../../types' interface llcNode { node: MemberAccessAstNode @@ -10,8 +10,8 @@ interface llcNode { export default class lowLevelCalls implements AnalyzerModule { llcNodes: llcNode[] = [] - name = `Low level calls: ` - description = `Should only be used by experienced devs` + name = 'Low level calls: ' + description = 'Should only be used by experienced devs' category: ModuleCategory = category.SECURITY algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -20,19 +20,19 @@ export default class lowLevelCalls implements AnalyzerModule { visit (node : MemberAccessAstNode): void { if (isLLCall(node)) { - this.llcNodes.push({node: node, type: lowLevelCallTypes.CALL}) + this.llcNodes.push({ node: node, type: lowLevelCallTypes.CALL }) } else if (isLLDelegatecall(node)) { - this.llcNodes.push({node: node, type: lowLevelCallTypes.DELEGATECALL}) + this.llcNodes.push({ node: node, type: lowLevelCallTypes.DELEGATECALL }) } else if (isLLSend(node)) { - this.llcNodes.push({node: node, type: lowLevelCallTypes.SEND}) + this.llcNodes.push({ node: node, type: lowLevelCallTypes.SEND }) } else if (isLLDelegatecall04(node)) { - this.llcNodes.push({node: node, type: lowLevelCallTypes.DELEGATECALL}) + this.llcNodes.push({ node: node, type: lowLevelCallTypes.DELEGATECALL }) } else if (isLLSend04(node)) { - this.llcNodes.push({node: node, type: lowLevelCallTypes.SEND}) + this.llcNodes.push({ node: node, type: lowLevelCallTypes.SEND }) } else if (isLLCall04(node)) { - this.llcNodes.push({node: node, type: lowLevelCallTypes.CALL}) + this.llcNodes.push({ node: node, type: lowLevelCallTypes.CALL }) } else if (isLLCallcode(node)) { - this.llcNodes.push({node: node, type: lowLevelCallTypes.CALLCODE}) + this.llcNodes.push({ node: node, type: lowLevelCallTypes.CALLCODE }) } } @@ -73,4 +73,3 @@ export default class lowLevelCalls implements AnalyzerModule { }) } } - diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/noReturn.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/noReturn.ts index 222fbaee5f..70588169d3 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/noReturn.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/noReturn.ts @@ -1,13 +1,15 @@ -import { default as category } from './categories' +import category from './categories' import { hasFunctionBody, getFullQuallyfiedFuncDefinitionIdent, getEffectedVariableName } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import AbstractAst from './abstractAstView' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst, - VisitFunction, ReportFunction, ReturnAstNode, AssignmentAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import AbstractAst from './abstractAstView' +import { + AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst, + VisitFunction, ReportFunction, ReturnAstNode, AssignmentAstNode, SupportedVersion +} from './../../types' export default class noReturn implements AnalyzerModule { - name = `No return: ` - description = `Function with 'returns' not returning` + name = 'No return: ' + description = 'Function with \'returns\' not returning' category: ModuleCategory = category.MISC algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -17,7 +19,7 @@ export default class noReturn implements AnalyzerModule { abstractAst: AbstractAst = new AbstractAst() visit: VisitFunction = this.abstractAst.build_visit( - (node: ReturnAstNode | AssignmentAstNode) => node.nodeType === "Return" || node.nodeType === "Assignment" + (node: ReturnAstNode | AssignmentAstNode) => node.nodeType === 'Return' || node.nodeType === 'Assignment' ) report: ReportFunction = this.abstractAst.build_report(this._report.bind(this)) @@ -30,12 +32,12 @@ export default class noReturn implements AnalyzerModule { if (this.hasNamedAndUnnamedReturns(func)) { warnings.push({ warning: `${funcName}: Mixing of named and unnamed return parameters is not advised.`, - location: func.node['src'] + location: func.node.src }) } else if (this.shouldReturn(func) && !(this.hasReturnStatement(func) || (this.hasNamedReturns(func) && this.hasAssignToAllNamedReturns(func)))) { warnings.push({ warning: `${funcName}: Defines a return type but never explicitly returns a value.`, - location: func.node['src'] + location: func.node.src }) } }) @@ -48,12 +50,12 @@ export default class noReturn implements AnalyzerModule { } private hasReturnStatement (func: FunctionHLAst): boolean { - return func.relevantNodes.filter(n => n.nodeType === "Return").length > 0 + return func.relevantNodes.filter(n => n.nodeType === 'Return').length > 0 } private hasAssignToAllNamedReturns (func: FunctionHLAst): boolean { const namedReturns: string[] = func.returns.filter(n => n.name.length > 0).map((n) => n.name) - const assignedVars: string[] = func.relevantNodes.filter(n => n.nodeType === "Assignment").map(getEffectedVariableName) + const assignedVars: string[] = func.relevantNodes.filter(n => n.nodeType === 'Assignment').map(getEffectedVariableName) const diff: string[] = namedReturns.filter(e => !assignedVars.includes(e)) return diff.length === 0 } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/selfdestruct.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/selfdestruct.ts index a5ac068cb8..e1ad68ecee 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/selfdestruct.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/selfdestruct.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' +import category from './categories' import { isStatement, isSelfdestructCall } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import AbstractAst from './abstractAstView' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VisitFunction, ReportFunction, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import AbstractAst from './abstractAstView' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, VisitFunction, ReportFunction, SupportedVersion } from './../../types' export default class selfdestruct implements AnalyzerModule { - name = `Selfdestruct: ` - description = `Contracts using destructed contract can be broken` + name = 'Selfdestruct: ' + description = 'Contracts using destructed contract can be broken' category: ModuleCategory = category.SECURITY algorithm: ModuleAlgorithm = algorithm.HEURISTIC version: SupportedVersion = { @@ -16,7 +16,7 @@ export default class selfdestruct implements AnalyzerModule { abstractAst: AbstractAst = new AbstractAst() visit: VisitFunction = this.abstractAst.build_visit( - (node: any) => isStatement(node) || (node.nodeType=== 'FunctionCall' && isSelfdestructCall(node)) + (node: any) => isStatement(node) || (node.nodeType === 'FunctionCall' && isSelfdestructCall(node)) ) report: ReportFunction = this.abstractAst.build_report(this._report.bind(this)) @@ -30,7 +30,7 @@ export default class selfdestruct implements AnalyzerModule { func.relevantNodes.forEach((node) => { if (isSelfdestructCall(node)) { warnings.push({ - warning: `Use of selfdestruct: Can block calling contracts unexpectedly. Be especially careful if this contract is planned to be used by other contracts (i.e. library contracts, interactions). Selfdestruction of the callee contract can leave callers in an inoperable state.`, + warning: 'Use of selfdestruct: Can block calling contracts unexpectedly. Be especially careful if this contract is planned to be used by other contracts (i.e. library contracts, interactions). Selfdestruction of the callee contract can leave callers in an inoperable state.', location: node.src, more: 'https://paritytech.io/blog/security-alert.html' }) @@ -38,7 +38,7 @@ export default class selfdestruct implements AnalyzerModule { } if (isStatement(node) && hasSelf) { warnings.push({ - warning: `Use of selfdestruct: No code after selfdestruct is executed. Selfdestruct is a terminal.`, + warning: 'Use of selfdestruct: No code after selfdestruct is executed. Selfdestruct is a terminal.', location: node.src, more: `https://solidity.readthedocs.io/en/${version}/introduction-to-smart-contracts.html#deactivate-and-self-destruct` }) diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/similarVariableNames.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/similarVariableNames.ts index e56057d3ed..35591dc8b1 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/similarVariableNames.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/similarVariableNames.ts @@ -1,11 +1,11 @@ -import { default as category } from './categories' +import category from './categories' import { getDeclaredVariableName, getFullQuallyfiedFuncDefinitionIdent } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import AbstractAst from './abstractAstView' +import algorithm from './algorithmCategories' +import AbstractAst from './abstractAstView' import { get } from 'fast-levenshtein' import { util } from '@remix-project/remix-lib' import { AstWalker } from '@remix-project/remix-astwalker' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst, VariableDeclarationAstNode, VisitFunction, ReportFunction, SupportedVersion} from './../../types' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, ContractHLAst, FunctionHLAst, VariableDeclarationAstNode, VisitFunction, ReportFunction, SupportedVersion } from './../../types' interface SimilarRecord { var1: string @@ -14,8 +14,8 @@ interface SimilarRecord { } export default class similarVariableNames implements AnalyzerModule { - name = `Similar variable names: ` - description = `Variable names are too similar` + name = 'Similar variable names: ' + description = 'Variable names are too similar' category: ModuleCategory = category.MISC algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -47,17 +47,17 @@ export default class similarVariableNames implements AnalyzerModule { const vars: string[] = this.getFunctionVariables(contract, func).map(getDeclaredVariableName) this.findSimilarVarNames(vars).map((sim) => { // check if function is implemented - if(func.node.implemented) { + if (func.node.implemented) { const astWalker = new AstWalker() const functionBody: any = func.node.body // Walk through all statements of function astWalker.walk(functionBody, (node) => { // check if these is an identifier node which is one of the tracked similar variables - if ((node.nodeType === 'Identifier' || node.nodeType === 'VariableDeclaration') - && (node.name === sim.var1 || node.name === sim.var2)) { + if ((node.nodeType === 'Identifier' || node.nodeType === 'VariableDeclaration') && + (node.name === sim.var1 || node.name === sim.var2)) { warnings.push({ warning: `${funcName} : Variables have very similar names "${sim.var1}" and "${sim.var2}". ${hasModifiersComments} ${multipleContractsWithSameNameComments}`, - location: node['src'] + location: node.src }) } return true @@ -73,9 +73,9 @@ export default class similarVariableNames implements AnalyzerModule { const similar: SimilarRecord[] = [] const comb: Record = {} vars.map((varName1: string) => vars.map((varName2: string) => { - if (varName1.length > 1 && varName2.length > 1 && - varName2 !== varName1 && !this.isCommonPrefixedVersion(varName1, varName2) && - !this.isCommonNrSuffixVersion(varName1, varName2) && + if (varName1.length > 1 && varName2.length > 1 && + varName2 !== varName1 && !this.isCommonPrefixedVersion(varName1, varName2) && + !this.isCommonNrSuffixVersion(varName1, varName2) && !(comb[varName1 + ';' + varName2] || comb[varName2 + ';' + varName1])) { comb[varName1 + ';' + varName2] = true const distance: number = get(varName1, varName2) diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.ts index 4120f37412..6d258d5909 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.ts @@ -1,9 +1,11 @@ 'use strict' -import { FunctionDefinitionAstNode, ModifierDefinitionAstNode, ParameterListAstNode, ForStatementAstNode, - WhileStatementAstNode, VariableDeclarationAstNode, ContractDefinitionAstNode, InheritanceSpecifierAstNode, - MemberAccessAstNode, BinaryOperationAstNode, FunctionCallAstNode, ExpressionStatementAstNode, UnaryOperationAstNode, - IdentifierAstNode, IndexAccessAstNode, BlockAstNode, AssignmentAstNode, InlineAssemblyAstNode, IfStatementAstNode, CompiledContractObj, ABIParameter, CompiledContract } from "../../types" +import { + FunctionDefinitionAstNode, ModifierDefinitionAstNode, ParameterListAstNode, ForStatementAstNode, + WhileStatementAstNode, VariableDeclarationAstNode, ContractDefinitionAstNode, InheritanceSpecifierAstNode, + MemberAccessAstNode, BinaryOperationAstNode, FunctionCallAstNode, ExpressionStatementAstNode, UnaryOperationAstNode, + IdentifierAstNode, IndexAccessAstNode, BlockAstNode, AssignmentAstNode, InlineAssemblyAstNode, IfStatementAstNode, CompiledContractObj, ABIParameter, CompiledContract +} from '../../types' import { util } from '@remix-project/remix-lib' type SpecialObjDetail = { @@ -34,35 +36,35 @@ const nodeTypes: Record = { FUNCTIONTYPENAME: 'FunctionTypeName', MAPPING: 'Mapping', ARRAYTYPENAME: 'ArrayTypeName', - INLINEASSEMBLY: 'InlineAssembly', + INLINEASSEMBLY: 'InlineAssembly', BLOCK: 'Block', - PLACEHOLDERSTATEMENT: 'PlaceholderStatement', + PLACEHOLDERSTATEMENT: 'PlaceholderStatement', IFSTATEMENT: 'IfStatement', - TRYCATCHCLAUSE: 'TryCatchClause', - TRYSTATEMENT: 'TryStatement', + TRYCATCHCLAUSE: 'TryCatchClause', + TRYSTATEMENT: 'TryStatement', WHILESTATEMENT: 'WhileStatement', DOWHILESTATEMENT: 'DoWhileStatement', FORSTATEMENT: 'ForStatement', - CONTINUE: 'Continue', - BREAK: 'Break', - RETURN: 'Return', - THROW: 'Throw', - EMITSTATEMENT: 'EmitStatement', - VARIABLEDECLARATIONSTATEMENT: 'VariableDeclarationStatement', + CONTINUE: 'Continue', + BREAK: 'Break', + RETURN: 'Return', + THROW: 'Throw', + EMITSTATEMENT: 'EmitStatement', + VARIABLEDECLARATIONSTATEMENT: 'VariableDeclarationStatement', EXPRESSIONSTATEMENT: 'ExpressionStatement', - CONDITIONAL: 'Conditional', + CONDITIONAL: 'Conditional', ASSIGNMENT: 'Assignment', - TUPLEEXPRESSION: 'TupleExpression', + TUPLEEXPRESSION: 'TupleExpression', UNARYOPERATION: 'UnaryOperation', BINARYOPERATION: 'BinaryOperation', FUNCTIONCALL: 'FunctionCall', FUNCTIONCALLOPTIONS: 'FunctionCallOptions', - NEWEXPRESSION: 'NewExpression', - MEMBERACCESS: 'MemberAccess', - INDEXACCESS: 'IndexAccess', - INDEXRANGEACCESS: 'IndexRangeAccess', - ELEMENTARYTYPENAMEEXPRESSION: 'ElementaryTypeNameExpression', - LITERAL: 'Literal', + NEWEXPRESSION: 'NewExpression', + MEMBERACCESS: 'MemberAccess', + INDEXACCESS: 'IndexAccess', + INDEXRANGEACCESS: 'IndexRangeAccess', + ELEMENTARYTYPENAMEEXPRESSION: 'ElementaryTypeNameExpression', + LITERAL: 'Literal', IDENTIFIER: 'Identifier', STRUCTUREDDOCUMENTATION: 'StructuredDocumentation' } @@ -184,7 +186,7 @@ function getFunctionCallType (func: FunctionCallAstNode): string { */ function getEffectedVariableName (effectNode: AssignmentAstNode | UnaryOperationAstNode): string { if (!isEffect(effectNode)) throw new Error('staticAnalysisCommon.js: not an effect Node') - if(effectNode.nodeType === 'Assignment' || effectNode.nodeType === 'UnaryOperation') { + if (effectNode.nodeType === 'Assignment' || effectNode.nodeType === 'UnaryOperation') { const IdentNode: IdentifierAstNode = findFirstSubNodeLTR(effectNode, exactMatch(nodeTypes.IDENTIFIER)) return IdentNode.name } else throw new Error('staticAnalysisCommon.js: wrong node type') @@ -334,7 +336,7 @@ function getDeclaredVariableType (varDeclNode: VariableDeclarationAstNode): stri * @return {list variable declaration} state variable node list */ function getStateVariableDeclarationsFromContractNode (contractNode: ContractDefinitionAstNode): VariableDeclarationAstNode[] { - return contractNode.nodes.filter(el => el.nodeType === "VariableDeclaration") + return contractNode.nodes.filter(el => el.nodeType === 'VariableDeclaration') } /** @@ -398,8 +400,7 @@ function getFunctionCallTypeParameterType (func: FunctionCallAstNode): string | function getLibraryCallContractName (node: FunctionCallAstNode): string | undefined { if (!isLibraryCall(node.expression)) throw new Error('staticAnalysisCommon.js: not a library call Node') const types: RegExpExecArray | null = new RegExp(basicRegex.LIBRARYTYPE).exec(node.expression.expression.typeDescriptions.typeString) - if(types) - return types[1] + if (types) { return types[1] } } /** @@ -444,29 +445,24 @@ function getFullQuallyfiedFuncDefinitionIdent (contract: ContractDefinitionAstNo function getUnAssignedTopLevelBinOps (subScope: BlockAstNode | IfStatementAstNode | WhileStatementAstNode | ForStatementAstNode): ExpressionStatementAstNode[] { let result: ExpressionStatementAstNode[] = [] - if(subScope && subScope.nodeType === 'Block') - result = subScope.statements.filter(isBinaryOpInExpression) + if (subScope && subScope.nodeType === 'Block') result = subScope.statements.filter(isBinaryOpInExpression) // for 'without braces' loops else if (subScope && subScope.nodeType && subScope.nodeType !== 'Block' && isSubScopeStatement(subScope)) { - if (subScope.nodeType === 'IfStatement'){ - if((subScope.trueBody && subScope.trueBody.nodeType === "ExpressionStatement" && isBinaryOpInExpression(subScope.trueBody))) - result.push(subScope.trueBody) - if (subScope.falseBody && subScope.falseBody.nodeType === "ExpressionStatement" && isBinaryOpInExpression(subScope.falseBody)) - result.push(subScope.falseBody) - } - else { - if(subScope.body && subScope.body.nodeType === "ExpressionStatement" && isBinaryOpInExpression(subScope.body)) - result.push(subScope.body) + if (subScope.nodeType === 'IfStatement') { + if ((subScope.trueBody && subScope.trueBody.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(subScope.trueBody))) { result.push(subScope.trueBody) } + if (subScope.falseBody && subScope.falseBody.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(subScope.falseBody)) { result.push(subScope.falseBody) } + } else { + if (subScope.body && subScope.body.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(subScope.body)) { result.push(subScope.body) } } } - return result + return result } // #################### Trivial Node Identification // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function isStatement (node: any): boolean { - return nodeType(node, 'Statement$') || node.nodeType === "Block" || node.nodeType === "Return" + return nodeType(node, 'Statement$') || node.nodeType === 'Block' || node.nodeType === 'Return' } // #################### Complex Node Identification @@ -505,7 +501,7 @@ function isDynamicArrayAccess (node: IdentifierAstNode): boolean { */ function isDynamicArrayLengthAccess (node: MemberAccessAstNode): boolean { return (node.memberName === 'length') && // accessing 'length' member - node.expression['typeDescriptions']['typeString'].indexOf('[]') !== -1 // member is accessed from dynamic array, notice [] without any number + node.expression.typeDescriptions.typeString.indexOf('[]') !== -1 // member is accessed from dynamic array, notice [] without any number } /** @@ -550,7 +546,7 @@ function isBuiltinFunctionCall (node: FunctionCallAstNode): boolean { * @return {bool} */ function isAbiNamespaceCall (node: FunctionCallAstNode): boolean { - return Object.keys(abiNamespace).some((key) => Object.prototype.hasOwnProperty.call(abiNamespace,key) && node.expression && isSpecialVariableAccess(node.expression, abiNamespace[key])) + return Object.keys(abiNamespace).some((key) => Object.prototype.hasOwnProperty.call(abiNamespace, key) && node.expression && isSpecialVariableAccess(node.expression, abiNamespace[key])) } /** @@ -576,7 +572,7 @@ function isAssertCall (node: FunctionCallAstNode): boolean { * @node {ASTNode} some AstNode * @return {bool} */ -function isRequireCall (node: FunctionCallAstNode): boolean { +function isRequireCall (node: FunctionCallAstNode): boolean { return isBuiltinFunctionCall(node) && getLocalCallName(node) === 'require' } @@ -597,7 +593,7 @@ function isStorageVariableDeclaration (node: VariableDeclarationAstNode): boolea function isInteraction (node: FunctionCallAstNode): boolean { return isLLCall(node.expression) || isLLSend(node.expression) || isExternalDirectCall(node) || isTransfer(node.expression) || isLLCall04(node.expression) || isLLSend04(node.expression) || - // to cover case of address.call.value.gas , See: inheritance.sol + // to cover case of address.call.value.gas , See: inheritance.sol (node.expression && node.expression.expression && isLLCall(node.expression.expression)) || (node.expression && node.expression.expression && isLLCall04(node.expression.expression)) } @@ -608,9 +604,9 @@ function isInteraction (node: FunctionCallAstNode): boolean { * @return {bool} */ function isEffect (node: AssignmentAstNode | UnaryOperationAstNode | InlineAssemblyAstNode): boolean { - return node.nodeType === "Assignment" || - (node.nodeType === "UnaryOperation" && (isPlusPlusUnaryOperation(node) || isMinusMinusUnaryOperation(node))) || - node.nodeType === "InlineAssembly" + return node.nodeType === 'Assignment' || + (node.nodeType === 'UnaryOperation' && (isPlusPlusUnaryOperation(node) || isMinusMinusUnaryOperation(node))) || + node.nodeType === 'InlineAssembly' } /** @@ -620,7 +616,7 @@ function isEffect (node: AssignmentAstNode | UnaryOperationAstNode | InlineAssem * @return {bool} */ function isWriteOnStateVariable (effectNode: AssignmentAstNode | InlineAssemblyAstNode | UnaryOperationAstNode, stateVariables: VariableDeclarationAstNode[]): boolean { - return effectNode.nodeType === "InlineAssembly" || (isEffect(effectNode) && isStateVariable(getEffectedVariableName(effectNode), stateVariables)) + return effectNode.nodeType === 'InlineAssembly' || (isEffect(effectNode) && isStateVariable(getEffectedVariableName(effectNode), stateVariables)) } /** @@ -648,7 +644,7 @@ function isConstantFunction (node: FunctionDefinitionAstNode): boolean { * @return {bool} */ function isVariableTurnedIntoGetter (varDeclNode: VariableDeclarationAstNode): boolean { - return varDeclNode.stateVariable && varDeclNode.visibility === 'public'; + return varDeclNode.stateVariable && varDeclNode.visibility === 'public' } /** @@ -666,7 +662,7 @@ function isPayableFunction (node: FunctionDefinitionAstNode): boolean { * @return {bool} */ function isConstructor (node: FunctionDefinitionAstNode): boolean { - return node.kind === "constructor" + return node.kind === 'constructor' } /** @@ -684,24 +680,21 @@ function isIntDivision (node: BinaryOperationAstNode): boolean { * @return {bool} */ function isSubScopeWithTopLevelUnAssignedBinOp (node: BlockAstNode | IfStatementAstNode | WhileStatementAstNode | ForStatementAstNode): boolean | undefined { - if(node.nodeType === 'Block') - return node.statements.some(isBinaryOpInExpression) + if (node.nodeType === 'Block') return node.statements.some(isBinaryOpInExpression) // for 'without braces' loops else if (node && node.nodeType && isSubScopeStatement(node)) { - if (node.nodeType === 'IfStatement') - return (node.trueBody && node.trueBody.nodeType === "ExpressionStatement" && isBinaryOpInExpression(node.trueBody)) || - (node.falseBody && node.falseBody.nodeType === "ExpressionStatement" && isBinaryOpInExpression(node.falseBody)) - else - return node.body && node.body.nodeType === "ExpressionStatement" && isBinaryOpInExpression(node.body) - } + if (node.nodeType === 'IfStatement') { + return (node.trueBody && node.trueBody.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(node.trueBody)) || + (node.falseBody && node.falseBody.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(node.falseBody)) + } else { return node.body && node.body.nodeType === 'ExpressionStatement' && isBinaryOpInExpression(node.body) } + } } function isSubScopeStatement (node: IfStatementAstNode | WhileStatementAstNode | ForStatementAstNode): boolean { - if(node.nodeType === 'IfStatement') + if (node.nodeType === 'IfStatement') { return (node.trueBody && node.trueBody.nodeType && !nodeType(node.trueBody, exactMatch(nodeTypes.BLOCK))) || (node.falseBody && node.falseBody.nodeType && !nodeType(node.falseBody, exactMatch(nodeTypes.BLOCK))) - else - return node.body && node.body.nodeType && !nodeType(node.body, exactMatch(nodeTypes.BLOCK)) + } else { return node.body && node.body.nodeType && !nodeType(node.body, exactMatch(nodeTypes.BLOCK)) } } /** @@ -710,7 +703,7 @@ function isSubScopeStatement (node: IfStatementAstNode | WhileStatementAstNode | * @return {bool} */ function isBinaryOpInExpression (node: ExpressionStatementAstNode): boolean { - return node.nodeType === "ExpressionStatement" && node.expression.nodeType === "BinaryOperation" + return node.nodeType === 'ExpressionStatement' && node.expression.nodeType === 'BinaryOperation' } /** @@ -791,7 +784,7 @@ function isExternalDirectCall (node: FunctionCallAstNode): boolean { * @return {bool} */ function isNowAccess (node: IdentifierAstNode): boolean { - return node.name === "now" && typeDescription(node, exactMatch(basicTypes.UINT)) + return node.name === 'now' && typeDescription(node, exactMatch(basicTypes.UINT)) } /** @@ -818,7 +811,7 @@ function isBlockTimestampAccess (node: MemberAccessAstNode): boolean { * @return {bool} */ function isBlockBlockHashAccess (node: FunctionCallAstNode): boolean { - return ( isBuiltinFunctionCall(node) && getLocalCallName(node) === 'blockhash' ) || + return (isBuiltinFunctionCall(node) && getLocalCallName(node) === 'blockhash') || isSpecialVariableAccess(node.expression, specialVariables.BLOCKHASH) } @@ -846,7 +839,7 @@ function isSuperLocalCall (node: MemberAccessAstNode): boolean { * @return {bool} */ function isLocalCall (node: FunctionCallAstNode): boolean { - return node.nodeType === 'FunctionCall' && node.kind === 'functionCall' && + return node.nodeType === 'FunctionCall' && node.kind === 'functionCall' && node.expression.nodeType === 'Identifier' && expressionTypeDescription(node, basicRegex.FUNCTIONTYPE) && !expressionTypeDescription(node, basicRegex.EXTERNALFUNCTIONTYPE) } @@ -873,8 +866,8 @@ function isLowLevelCall (node: MemberAccessAstNode): boolean { */ function isLLSend04 (node: MemberAccessAstNode): boolean { return isMemberAccess(node, - exactMatch(util.escapeRegExp(lowLevelCallTypes.SEND.type)), - undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.SEND.ident)) + exactMatch(util.escapeRegExp(lowLevelCallTypes.SEND.type)), + undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.SEND.ident)) } /** @@ -884,8 +877,8 @@ function isLLSend04 (node: MemberAccessAstNode): boolean { */ function isLLSend (node: MemberAccessAstNode): boolean { return isMemberAccess(node, - exactMatch(util.escapeRegExp(lowLevelCallTypes.SEND.type)), - undefined, exactMatch(basicTypes.PAYABLE_ADDRESS), exactMatch(lowLevelCallTypes.SEND.ident)) + exactMatch(util.escapeRegExp(lowLevelCallTypes.SEND.type)), + undefined, exactMatch(basicTypes.PAYABLE_ADDRESS), exactMatch(lowLevelCallTypes.SEND.ident)) } /** @@ -895,8 +888,8 @@ function isLLSend (node: MemberAccessAstNode): boolean { */ function isLLCall (node: MemberAccessAstNode): boolean { return isMemberAccess(node, - exactMatch(util.escapeRegExp(lowLevelCallTypes.CALL.type)), - undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALL.ident)) || + exactMatch(util.escapeRegExp(lowLevelCallTypes.CALL.type)), + undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALL.ident)) || isMemberAccess(node, exactMatch(util.escapeRegExp(lowLevelCallTypes.CALL.type)), undefined, exactMatch(basicTypes.PAYABLE_ADDRESS), exactMatch(lowLevelCallTypes.CALL.ident)) @@ -909,8 +902,8 @@ function isLLCall (node: MemberAccessAstNode): boolean { */ function isLLCall04 (node: MemberAccessAstNode): boolean { return isMemberAccess(node, - exactMatch(util.escapeRegExp(lowLevelCallTypes['CALL-0.4'].type)), - undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes['CALL-0.4'].ident)) + exactMatch(util.escapeRegExp(lowLevelCallTypes['CALL-0.4'].type)), + undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes['CALL-0.4'].ident)) } /** @@ -920,8 +913,8 @@ function isLLCall04 (node: MemberAccessAstNode): boolean { */ function isLLCallcode (node: MemberAccessAstNode): boolean { return isMemberAccess(node, - exactMatch(util.escapeRegExp(lowLevelCallTypes.CALLCODE.type)), - undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALLCODE.ident)) + exactMatch(util.escapeRegExp(lowLevelCallTypes.CALLCODE.type)), + undefined, exactMatch(basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.CALLCODE.ident)) } /** @@ -931,8 +924,8 @@ function isLLCallcode (node: MemberAccessAstNode): boolean { */ function isLLDelegatecall (node: MemberAccessAstNode): boolean { return isMemberAccess(node, - exactMatch(util.escapeRegExp(lowLevelCallTypes.DELEGATECALL.type)), - undefined, matches(basicTypes.PAYABLE_ADDRESS, basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.DELEGATECALL.ident)) + exactMatch(util.escapeRegExp(lowLevelCallTypes.DELEGATECALL.type)), + undefined, matches(basicTypes.PAYABLE_ADDRESS, basicTypes.ADDRESS), exactMatch(lowLevelCallTypes.DELEGATECALL.ident)) } /** @@ -942,8 +935,8 @@ function isLLDelegatecall (node: MemberAccessAstNode): boolean { */ function isLLDelegatecall04 (node: MemberAccessAstNode): boolean { return isMemberAccess(node, - exactMatch(util.escapeRegExp(lowLevelCallTypes['DELEGATECALL-0.4'].type)), - undefined, matches(basicTypes.PAYABLE_ADDRESS, basicTypes.ADDRESS), exactMatch(lowLevelCallTypes['DELEGATECALL-0.4'].ident)) + exactMatch(util.escapeRegExp(lowLevelCallTypes['DELEGATECALL-0.4'].type)), + undefined, matches(basicTypes.PAYABLE_ADDRESS, basicTypes.ADDRESS), exactMatch(lowLevelCallTypes['DELEGATECALL-0.4'].ident)) } /** @@ -953,8 +946,8 @@ function isLLDelegatecall04 (node: MemberAccessAstNode): boolean { */ function isTransfer (node: MemberAccessAstNode): boolean { return isMemberAccess(node, - exactMatch(util.escapeRegExp(lowLevelCallTypes.TRANSFER.type)), - undefined, matches(basicTypes.ADDRESS, basicTypes.PAYABLE_ADDRESS), exactMatch(lowLevelCallTypes.TRANSFER.ident)) + exactMatch(util.escapeRegExp(lowLevelCallTypes.TRANSFER.type)), + undefined, matches(basicTypes.ADDRESS, basicTypes.PAYABLE_ADDRESS), exactMatch(lowLevelCallTypes.TRANSFER.ident)) } function isStringToBytesConversion (node: FunctionCallAstNode): boolean { @@ -962,7 +955,7 @@ function isStringToBytesConversion (node: FunctionCallAstNode): boolean { } function isExplicitCast (node: FunctionCallAstNode, castFromType: string, castToType: string): boolean { - return node.kind === "typeConversion" && + return node.kind === 'typeConversion' && nodeType(node.expression, exactMatch(nodeTypes.ELEMENTARYTYPENAMEEXPRESSION)) && node.expression.typeName === castToType && nodeType(node.arguments[0], exactMatch(nodeTypes.IDENTIFIER)) && typeDescription(node.arguments[0], castFromType) } @@ -976,7 +969,7 @@ function isBytesLengthCheck (node: MemberAccessAstNode): boolean { * @node {ASTNode} some AstNode * @return {bool} */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function isLoop (node: any): boolean { return nodeType(node, exactMatch(nodeTypes.FORSTATEMENT)) || nodeType(node, exactMatch(nodeTypes.WHILESTATEMENT)) || @@ -986,7 +979,7 @@ function isLoop (node: any): boolean { // #################### Complex Node Identification - Private function isMemberAccess (node: MemberAccessAstNode, retType: string, accessor: string| undefined, accessorType: string, memberName: string | undefined): boolean { - if(node && nodeType(node, exactMatch('MemberAccess'))) { + if (node && nodeType(node, exactMatch('MemberAccess'))) { const nodeTypeDef: boolean = typeDescription(node, retType) const nodeMemName: boolean = memName(node, memberName) const nodeExpMemName: boolean = memName(node.expression, accessor) @@ -1003,12 +996,12 @@ function isSpecialVariableAccess (node: MemberAccessAstNode, varType: SpecialObj // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function expressionTypeDescription (node: any, typeRegex: string): boolean { - return new RegExp(typeRegex).test(node.expression.typeDescriptions.typeString) + return new RegExp(typeRegex).test(node.expression.typeDescriptions.typeString) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function typeDescription (node: any, typeRegex: string): boolean { - return new RegExp(typeRegex).test(node.typeDescriptions.typeString) + return new RegExp(typeRegex).test(node.typeDescriptions.typeString) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types @@ -1018,7 +1011,7 @@ function nodeType (node: any, typeRegex: string): boolean { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types function nodeTypeIn (node: any, typeRegex: string[]): boolean { - return typeRegex.some((typeRegex) => nodeType (node, typeRegex)) + return typeRegex.some((typeRegex) => nodeType(node, typeRegex)) } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types @@ -1053,20 +1046,7 @@ function matches (...fnArgs: any[]): string { * Note: developed keeping identifier node search in mind to get first identifier node from left in subscope */ function findFirstSubNodeLTR (node: any, type: string): any { - if(node.nodeType && nodeType(node, type)) - return node - - else if(node.nodeType && nodeType(node, exactMatch('Assignment'))) - return findFirstSubNodeLTR(node.leftHandSide, type) - - else if(node.nodeType && nodeType(node, exactMatch('MemberAccess'))) - return findFirstSubNodeLTR(node.expression, type) - - else if(node.nodeType && nodeType(node, exactMatch('IndexAccess'))) - return findFirstSubNodeLTR(node.baseExpression, type) - - else if(node.nodeType && nodeType(node, exactMatch('UnaryOperation'))) - return findFirstSubNodeLTR(node.subExpression, type) + if (node.nodeType && nodeType(node, type)) { return node } else if (node.nodeType && nodeType(node, exactMatch('Assignment'))) { return findFirstSubNodeLTR(node.leftHandSide, type) } else if (node.nodeType && nodeType(node, exactMatch('MemberAccess'))) { return findFirstSubNodeLTR(node.expression, type) } else if (node.nodeType && nodeType(node, exactMatch('IndexAccess'))) { return findFirstSubNodeLTR(node.baseExpression, type) } else if (node.nodeType && nodeType(node, exactMatch('UnaryOperation'))) { return findFirstSubNodeLTR(node.subExpression, type) } } /** @@ -1087,45 +1067,41 @@ function buildAbiSignature (funName: string, paramTypes: any[]): string { } // To create the method signature similar to contract.evm.gasEstimates.external object -// For address payable, return address -function getMethodParamsSplittedTypeDesc(node: FunctionDefinitionAstNode, contracts: CompiledContractObj): string[] { +// For address payable, return address +function getMethodParamsSplittedTypeDesc (node: FunctionDefinitionAstNode, contracts: CompiledContractObj): string[] { return node.parameters.parameters.map((varNode, varIndex) => { - let finalTypeString; + let finalTypeString const typeString = varNode.typeDescriptions.typeString - if(typeString.includes('struct')) { + if (typeString.includes('struct')) { const fnName = node.name for (const filename in contracts) { for (const contractName in contracts[filename]) { const methodABI = contracts[filename][contractName].abi - .find(e => e.name === fnName && e.inputs?.length && - e.inputs[varIndex]['type'].includes('tuple') && + .find(e => e.name === fnName && e.inputs?.length && + e.inputs[varIndex]['type'].includes('tuple') && e.inputs[varIndex]['internalType'] === typeString) - if(methodABI && methodABI.inputs) { + if (methodABI && methodABI.inputs) { const inputs = methodABI.inputs[varIndex] const typeStr = getTypeStringFromComponents(inputs['components']) finalTypeString = typeStr + inputs['type'].replace('tuple', '') } } } - } else - finalTypeString = typeString.split(' ')[0] + } else { finalTypeString = typeString.split(' ')[0] } return finalTypeString }) } -function getTypeStringFromComponents(components: ABIParameter[]) { +function getTypeStringFromComponents (components: ABIParameter[]) { let typeString = '(' - for(let i=0; i < components.length; i++) { + for (let i = 0; i < components.length; i++) { const param = components[i] - if(param.type.includes('tuple') && param.components && param.components.length > 0){ + if (param.type.includes('tuple') && param.components && param.components.length > 0) { typeString = typeString + getTypeStringFromComponents(param.components) typeString = typeString + param.type.replace('tuple', '') - } - else - typeString = typeString + param.type + } else { typeString = typeString + param.type } - if(i !== components.length - 1) - typeString = typeString + ',' + if (i !== components.length - 1) { typeString = typeString + ',' } } typeString = typeString + ')' return typeString @@ -1136,18 +1112,17 @@ function getTypeStringFromComponents(components: ABIParameter[]) { * This is used to redirect the user to specific version of Solidity documentation * @param contractFiles compiled contract object */ -function getCompilerVersion(contractFiles: CompiledContractObj): string { +function getCompilerVersion (contractFiles: CompiledContractObj): string { let version = 'latest' const fileNames: string[] = Object.keys(contractFiles) const contracts = contractFiles[fileNames[0]] const contractNames: string[] = Object.keys(contracts) const contract: CompiledContract = contracts[contractNames[0]] // For some compiler/contract, metadata is "" - if(contract && contract.metadata) { + if (contract && contract.metadata) { const metadata = JSON.parse(contract.metadata) const compilerVersion: string = metadata.compiler.version - if(!compilerVersion.includes('nightly')) - version = 'v' + compilerVersion.split('+commit')[0] + if (!compilerVersion.includes('nightly')) { version = 'v' + compilerVersion.split('+commit')[0] } } return version } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/stringBytesLength.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/stringBytesLength.ts index 91a9ca4afc..57c02b84dd 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/stringBytesLength.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/stringBytesLength.ts @@ -1,11 +1,11 @@ -import { default as category } from './categories' -import { default as algorithm } from './algorithmCategories' +import category from './categories' +import algorithm from './algorithmCategories' import { isStringToBytesConversion, isBytesLengthCheck, getCompilerVersion } from './staticAnalysisCommon' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, FunctionCallAstNode, SupportedVersion} from './../../types' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, FunctionCallAstNode, SupportedVersion } from './../../types' export default class stringBytesLength implements AnalyzerModule { - name = `String length: ` - description = `Bytes length != String length` + name = 'String length: ' + description = 'Bytes length != String length' category: ModuleCategory = category.MISC algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -16,8 +16,8 @@ export default class stringBytesLength implements AnalyzerModule { bytesLengthChecks: MemberAccessAstNode[] = [] visit (node: FunctionCallAstNode | MemberAccessAstNode): void { - if (node.nodeType === "FunctionCall" && isStringToBytesConversion(node)) this.stringToBytesConversions.push(node) - else if (node.nodeType === "MemberAccess" && isBytesLengthCheck(node)) this.bytesLengthChecks.push(node) + if (node.nodeType === 'FunctionCall' && isStringToBytesConversion(node)) this.stringToBytesConversions.push(node) + else if (node.nodeType === 'MemberAccess' && isBytesLengthCheck(node)) this.bytesLengthChecks.push(node) } // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -25,7 +25,7 @@ export default class stringBytesLength implements AnalyzerModule { const version = getCompilerVersion(compilationResults.contracts) if (this.stringToBytesConversions.length > 0 && this.bytesLengthChecks.length > 0) { return [{ - warning: `"bytes" and "string" lengths are not the same since strings are assumed to be UTF-8 encoded (according to the ABI defintion) therefore one character is not nessesarily encoded in one byte of data.`, + warning: '"bytes" and "string" lengths are not the same since strings are assumed to be UTF-8 encoded (according to the ABI defintion) therefore one character is not nessesarily encoded in one byte of data.', location: this.bytesLengthChecks[0].src, more: `https://solidity.readthedocs.io/en/${version}/abi-spec.html#argument-encoding` }] diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/thisLocal.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/thisLocal.ts index 3abcda5816..9c13b4c2ac 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/thisLocal.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/thisLocal.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' +import category from './categories' import { isThisLocalCall, getCompilerVersion } from './staticAnalysisCommon' -import { default as algorithm } from './algorithmCategories' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion} from './../../types' +import algorithm from './algorithmCategories' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion } from './../../types' export default class thisLocal implements AnalyzerModule { warningNodes: MemberAccessAstNode[] = [] - name = `This on local calls: ` - description = `Invocation of local functions via 'this'` + name = 'This on local calls: ' + description = 'Invocation of local functions via \'this\'' category: ModuleCategory = category.GAS algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -22,7 +22,7 @@ export default class thisLocal implements AnalyzerModule { const version = getCompilerVersion(compilationResults.contracts) return this.warningNodes.map(function (item, i) { return { - warning: `Use of "this" for local functions: Never use "this" to call functions in the same contract, it only consumes more gas than normal local calls.`, + warning: 'Use of "this" for local functions: Never use "this" to call functions in the same contract, it only consumes more gas than normal local calls.', location: item.src, more: `https://solidity.readthedocs.io/en/${version}/control-structures.html#external-function-calls` } diff --git a/libs/remix-analyzer/src/solidity-analyzer/modules/txOrigin.ts b/libs/remix-analyzer/src/solidity-analyzer/modules/txOrigin.ts index c4f6570387..1a7a0cd0d7 100644 --- a/libs/remix-analyzer/src/solidity-analyzer/modules/txOrigin.ts +++ b/libs/remix-analyzer/src/solidity-analyzer/modules/txOrigin.ts @@ -1,12 +1,12 @@ -import { default as category } from './categories' -import { default as algorithm } from './algorithmCategories' +import category from './categories' +import algorithm from './algorithmCategories' import { isTxOriginAccess, getCompilerVersion } from './staticAnalysisCommon' -import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion} from './../../types' +import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, SupportedVersion } from './../../types' export default class txOrigin implements AnalyzerModule { txOriginNodes: MemberAccessAstNode[] = [] - name = `Transaction origin: ` - description = `'tx.origin' used` + name = 'Transaction origin: ' + description = '\'tx.origin\' used' category: ModuleCategory = category.SECURITY algorithm: ModuleAlgorithm = algorithm.EXACT version: SupportedVersion = { @@ -15,7 +15,6 @@ export default class txOrigin implements AnalyzerModule { visit (node: MemberAccessAstNode): void { if (isTxOriginAccess(node)) this.txOriginNodes.push(node) - } // eslint-disable-next-line @typescript-eslint/no-unused-vars diff --git a/libs/remix-analyzer/src/types.ts b/libs/remix-analyzer/src/types.ts index 5eaccca5c9..eab758b04a 100644 --- a/libs/remix-analyzer/src/types.ts +++ b/libs/remix-analyzer/src/types.ts @@ -39,9 +39,9 @@ export interface ReportObj { // s:l:f -// Where, -// s is the byte-offset to the start of the range in the source file, -// l is the length of the source range in bytes and +// Where, +// s is the byte-offset to the start of the range in the source file, +// l is the length of the source range in bytes and // f is the source index mentioned above. export interface AnalysisReportObj { @@ -57,7 +57,7 @@ export type AnalysisReport = { } export interface CompilationResult { - error?: CompilationError, + error?: CompilationError, /** not present if no errors/warnings were encountered */ errors?: CompilationError[] /** This contains the file-level outputs. In can be limited/filtered by the outputSelection settings */ @@ -121,9 +121,9 @@ export interface ContractCallGraph { functions: Record } -///////////////////////////////////////////////////////////// -///////////// Specfic AST Nodes ///////////////////////////// -///////////////////////////////////////////////////////////// +/// ////////////////////////////////////////////////////////// +/// ////////// Specfic AST Nodes ///////////////////////////// +/// ////////////////////////////////////////////////////////// interface TypeDescription { typeIdentifier: string @@ -629,10 +629,9 @@ export interface CommonAstNode { [x: string]: any } - -///////////////////////////////////////////////////////// -///////////// YUL AST Nodes ///////////////////////////// -///////////////////////////////////////////////////////// +/// ////////////////////////////////////////////////////// +/// ////////// YUL AST Nodes ///////////////////////////// +/// ////////////////////////////////////////////////////// export interface YulTypedNameAstNode { name: string @@ -673,13 +672,12 @@ export interface CommonYulAstNode { src: string [x: string]: any } - - - /////////// - // ERROR // - /////////// - - export interface CompilationError { + +/// //////// +// ERROR // +/// //////// + +export interface CompilationError { /** Location within the source file */ sourceLocation?: { file: string @@ -696,7 +694,7 @@ export interface CommonYulAstNode { /** the message formatted with source location */ formattedMessage?: string } - + type CompilationErrorType = | 'JSONError' | 'IOError' @@ -711,21 +709,21 @@ export interface CommonYulAstNode { | 'CompilerError' | 'FatalError' | 'Warning' - - //////////// - // SOURCE // - //////////// - export interface CompilationSource { + +/// ///////// +// SOURCE // +/// ///////// +export interface CompilationSource { /** Identifier of the source (used in source maps) */ id: number /** The AST object */ ast: AstNode } - - ///////// - // AST // - ///////// - export interface AstNode { + +/// ////// +// AST // +/// ////// +export interface AstNode { absolutePath?: string exportedSymbols?: Record id: number @@ -739,8 +737,8 @@ export interface CommonYulAstNode { symbolAliases?: Array [x: string]: any } - - export interface AstNodeAtt { + +export interface AstNodeAtt { operator?: string string?: null type?: string @@ -753,11 +751,11 @@ export interface CommonYulAstNode { absolutePath?: string [x: string]: any } - - ////////////// - // CONTRACT // - ////////////// - export interface CompiledContract { + +/// /////////// +// CONTRACT // +/// /////////// +export interface CompiledContract { /** The Ethereum Contract ABI. If empty, it is represented as an empty array. */ abi: ABIDescription[] // See the Metadata Output documentation (serialised JSON string) @@ -802,13 +800,13 @@ export interface CommonYulAstNode { wasm: string } } - - ///////// - // ABI // - ///////// - export type ABIDescription = FunctionDescription | EventDescription - - export interface FunctionDescription { + +/// ////// +// ABI // +/// ////// +export type ABIDescription = FunctionDescription | EventDescription + +export interface FunctionDescription { /** Type of the method. default is 'function' */ type?: 'function' | 'constructor' | 'fallback' | 'receive' /** The name of the function. Constructor and fallback function never have name */ @@ -824,8 +822,8 @@ export interface CommonYulAstNode { /** true if function is either pure or view, false otherwise. Default is false */ constant?: boolean } - - export interface EventDescription { + +export interface EventDescription { type: 'event' name: string inputs: ABIParameter & @@ -836,8 +834,8 @@ export interface CommonYulAstNode { /** true if the event was declared as anonymous. */ anonymous: boolean } - - export interface ABIParameter { + +export interface ABIParameter { internalType: string /** The name of the parameter */ name: string @@ -846,8 +844,8 @@ export interface CommonYulAstNode { /** Used for tuple types */ components?: ABIParameter[] } - - export type ABITypeParameter = + +export type ABITypeParameter = | 'uint' | 'uint[]' // TODO : add | 'int' @@ -868,38 +866,38 @@ export interface CommonYulAstNode { | 'tuple[]' | string // Fallback -/////////////////////////// - // NATURAL SPECIFICATION // - /////////////////////////// - - // Userdoc - export interface UserDocumentation { +/// //////////////////////// +// NATURAL SPECIFICATION // +/// //////////////////////// + +// Userdoc +export interface UserDocumentation { methods: UserMethodList notice: string } - - export type UserMethodList = { + +export type UserMethodList = { [functionIdentifier: string]: UserMethodDoc } & { 'constructor'?: string } - export interface UserMethodDoc { +export interface UserMethodDoc { notice: string } - - // Devdoc - export interface DeveloperDocumentation { + +// Devdoc +export interface DeveloperDocumentation { author: string title: string details: string methods: DevMethodList } - - export interface DevMethodList { + +export interface DevMethodList { [functionIdentifier: string]: DevMethodDoc } - - export interface DevMethodDoc { + +export interface DevMethodDoc { author: string details: string return: string @@ -907,11 +905,11 @@ export interface CommonYulAstNode { [param: string]: string } } - - ////////////// - // BYTECODE // - ////////////// - export interface BytecodeObject { + +/// /////////// +// BYTECODE // +/// /////////// +export interface BytecodeObject { /** The bytecode as a hex string. */ object: string /** Opcodes list */ @@ -925,4 +923,4 @@ export interface CommonYulAstNode { [library: string]: { start: number; length: number }[] } } - } \ No newline at end of file + }