Merge pull request #1372 from ethereum/syntax_updates2

Syntax updates2
pull/7/head
Iuri Matias 5 years ago committed by GitHub
commit 1f74b65149
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2190
      remix-analyzer/package-lock.json
  2. 18
      remix-analyzer/src/solidity-analyzer/modules/abstractAstView.js
  3. 12
      remix-analyzer/src/solidity-analyzer/modules/assignAndCompare.js
  4. 12
      remix-analyzer/src/solidity-analyzer/modules/blockBlockhash.js
  5. 14
      remix-analyzer/src/solidity-analyzer/modules/blockTimestamp.js
  6. 30
      remix-analyzer/src/solidity-analyzer/modules/checksEffectsInteraction.js
  7. 26
      remix-analyzer/src/solidity-analyzer/modules/constantFunctions.js
  8. 10
      remix-analyzer/src/solidity-analyzer/modules/deleteDynamicArrays.js
  9. 8
      remix-analyzer/src/solidity-analyzer/modules/deleteFromDynamicArray.js
  10. 20
      remix-analyzer/src/solidity-analyzer/modules/erc20Decimals.js
  11. 12
      remix-analyzer/src/solidity-analyzer/modules/etherTransferInLoop.js
  12. 12
      remix-analyzer/src/solidity-analyzer/modules/forLoopIteratesOverDynamicArray.js
  13. 32
      remix-analyzer/src/solidity-analyzer/modules/functionCallGraph.js
  14. 20
      remix-analyzer/src/solidity-analyzer/modules/gasCosts.js
  15. 10
      remix-analyzer/src/solidity-analyzer/modules/guardConditions.js
  16. 10
      remix-analyzer/src/solidity-analyzer/modules/inlineAssembly.js
  17. 12
      remix-analyzer/src/solidity-analyzer/modules/intDivisionTruncate.js
  18. 16
      remix-analyzer/src/solidity-analyzer/modules/lowLevelCalls.js
  19. 22
      remix-analyzer/src/solidity-analyzer/modules/noReturn.js
  20. 14
      remix-analyzer/src/solidity-analyzer/modules/selfdestruct.js
  21. 39
      remix-analyzer/src/solidity-analyzer/modules/similarVariableNames.js
  22. 40
      remix-analyzer/src/solidity-analyzer/modules/staticAnalysisCommon.js
  23. 9
      remix-analyzer/src/solidity-analyzer/modules/stringBytesLength.js
  24. 10
      remix-analyzer/src/solidity-analyzer/modules/thisLocal.js
  25. 10
      remix-analyzer/src/solidity-analyzer/modules/txOrigin.js
  26. 52
      remix-debug/package-lock.json
  27. 2
      remix-debug/src/debugger/solidityState.js
  28. 52
      remix-lib/index.js
  29. 8
      remix-lib/src/astWalker.js
  30. 28
      remix-lib/src/code/breakpointManager.js
  31. 40
      remix-lib/src/code/codeManager.js
  32. 21
      remix-lib/src/code/codeResolver.js
  33. 30
      remix-lib/src/code/codeUtils.js
  34. 26
      remix-lib/src/code/disassembler.js
  35. 6
      remix-lib/src/code/opcodes.js
  36. 6
      remix-lib/src/eventManager.js
  37. 32
      remix-lib/src/execution/eventsDecoder.js
  38. 87
      remix-lib/src/execution/execution-context.js
  39. 2
      remix-lib/src/execution/txExecution.js
  40. 104
      remix-lib/src/execution/txFormat.js
  41. 37
      remix-lib/src/execution/txHelper.js
  42. 69
      remix-lib/src/execution/txListener.js
  43. 50
      remix-lib/src/execution/txRunner.js
  44. 10
      remix-lib/src/execution/typeConversion.js
  45. 9
      remix-lib/src/helpers/traceHelper.js
  46. 24
      remix-lib/src/helpers/uiHelper.js
  47. 8
      remix-lib/src/init.js
  48. 8
      remix-lib/src/offsetToLineColumnConverter.js
  49. 32
      remix-lib/src/sourceLocationTracker.js
  50. 50
      remix-lib/src/sourceMappingDecoder.js
  51. 2
      remix-lib/src/storage.js
  52. 36
      remix-lib/src/trace/traceAnalyser.js
  53. 18
      remix-lib/src/trace/traceCache.js
  54. 58
      remix-lib/src/trace/traceManager.js
  55. 2
      remix-lib/src/trace/traceRetriever.js
  56. 18
      remix-lib/src/trace/traceStepManager.js
  57. 62
      remix-lib/src/util.js
  58. 13
      remix-lib/src/web3Provider/dummyProvider.js
  59. 8
      remix-lib/src/web3Provider/web3Providers.js
  60. 99
      remix-lib/src/web3Provider/web3VmProvider.js
  61. 10
      remix-lib/test/astwalker.js
  62. 24
      remix-lib/test/codeManager.js
  63. 8
      remix-lib/test/disassembler.js
  64. 12
      remix-lib/test/eventManager.js
  65. 2
      remix-lib/test/init.js
  66. 2
      remix-lib/test/resources/ast.js
  67. 2
      remix-lib/test/resources/sourceMapping.js
  68. 6
      remix-lib/test/resources/testWeb3.js
  69. 34
      remix-lib/test/sourceMappingDecoder.js
  70. 22
      remix-lib/test/traceManager.js
  71. 120
      remix-lib/test/txFormat.js
  72. 8
      remix-lib/test/txHelper.js
  73. 20
      remix-lib/test/util.js
  74. 4
      remix-solidity/index.js
  75. 1205
      remix-solidity/package-lock.json
  76. 1
      remix-solidity/package.json
  77. 12
      remix-solidity/src/compiler/compiler-worker.js
  78. 80
      remix-solidity/src/compiler/compiler.js
  79. 6
      remix-solidity/src/compiler/txHelper.js

File diff suppressed because it is too large Load Diff

@ -1,5 +1,5 @@
var common = require('./staticAnalysisCommon')
var AstWalker = require('remix-lib').AstWalker
const common = require('./staticAnalysisCommon')
const AstWalker = require('remix-lib').AstWalker
function abstractAstView () {
this.contracts = []
@ -56,8 +56,8 @@ abstractAstView.prototype.build_visit = function (relevantNodeFilter) {
stateVariables: common.getStateVariableDeclarationsFormContractNode(node)
})
} else if (common.isInheritanceSpecifier(node)) {
var currentContract = getCurrentContract(that)
var inheritsFromName = common.getInheritsFromName(node)
const currentContract = getCurrentContract(that)
const inheritsFromName = common.getInheritsFromName(node)
currentContract.inheritsFrom.push(inheritsFromName)
} else if (common.isFunctionDefinition(node)) {
setCurrentFunction(that, {
@ -85,7 +85,7 @@ abstractAstView.prototype.build_visit = function (relevantNodeFilter) {
if (!that.isFunctionNotModifier) throw new Error('abstractAstView.js: Found modifier invocation outside of function scope.')
getCurrentFunction(that).modifierInvocations.push(node)
} else if (relevantNodeFilter(node)) {
var scope = (that.isFunctionNotModifier) ? getCurrentFunction(that) : getCurrentModifier(that)
let scope = (that.isFunctionNotModifier) ? getCurrentFunction(that) : getCurrentModifier(that)
if (scope) {
scope.relevantNodes.push(node)
} else {
@ -111,10 +111,11 @@ function resolveStateVariablesInHierarchy (contracts) {
resolveStateVariablesInHierarchyForContract(c, contracts)
})
}
function resolveStateVariablesInHierarchyForContract (currentContract, contracts) {
currentContract.inheritsFrom.map((inheritsFromName) => {
// add variables from inherited contracts
var inheritsFrom = contracts.find((contract) => common.getContractName(contract.node) === inheritsFromName)
const inheritsFrom = contracts.find((contract) => common.getContractName(contract.node) === inheritsFromName)
if (inheritsFrom) {
currentContract.stateVariables = currentContract.stateVariables.concat(inheritsFrom.stateVariables)
} else {
@ -122,8 +123,9 @@ function resolveStateVariablesInHierarchyForContract (currentContract, contracts
}
})
}
function setCurrentContract (that, contract) {
var name = common.getContractName(contract.node)
const name = common.getContractName(contract.node)
if (that.contracts.map((c) => common.getContractName(c.node)).filter((n) => n === name).length > 0) {
console.log('abstractAstView.js: two or more contracts with the same name dectected, import aliases not supported at the moment')
that.multipleContractsWithSameName = true
@ -167,7 +169,7 @@ function getReturnParameters (funcNode) {
}
function getLocalVariables (funcNode) {
var locals = []
const locals = []
new AstWalker().walk(funcNode, {'*': function (node) {
if (common.isVariableDeclaration(node)) locals.push(node)
return true

@ -1,8 +1,8 @@
var name = 'Result not used: '
var desc = 'The result of an operation was not used.'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'Result not used: '
const desc = 'The result of an operation was not used.'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function assignAndCompare () {
this.warningNodes = []
@ -13,7 +13,7 @@ assignAndCompare.prototype.visit = function (node) {
}
assignAndCompare.prototype.report = function (compilationResults) {
return this.warningNodes.map(function (item, i) {
return this.warningNodes.map((item, i) => {
return {
warning: 'A binary operation yields a value that is not used in the following. This is often caused by confusing assignment (=) and comparison (==).',
location: item.src

@ -1,8 +1,8 @@
var name = 'Block.blockhash usage: '
var desc = 'Semantics maybe unclear'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'Block.blockhash usage: '
const desc = 'Semantics maybe unclear'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function blockBlockhash () {
this.warningNodes = []
@ -13,7 +13,7 @@ blockBlockhash.prototype.visit = function (node) {
}
blockBlockhash.prototype.report = function (compilationResults) {
return this.warningNodes.map(function (item, i) {
return this.warningNodes.map((item, i) => {
return {
warning: `use of "block.blockhash": "block.blockhash" is used to access the last 256 block hashes.
A miner computes the block hash by "summing up" the information in the current block mined.

@ -1,8 +1,8 @@
var name = 'Block timestamp: '
var desc = 'Semantics maybe unclear'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'Block timestamp: '
const desc = 'Semantics maybe unclear'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function blockTimestamp () {
this.warningNowNodes = []
@ -15,14 +15,14 @@ blockTimestamp.prototype.visit = function (node) {
}
blockTimestamp.prototype.report = function (compilationResults) {
return this.warningNowNodes.map(function (item, i) {
return this.warningNowNodes.map((item, i) => {
return {
warning: `use of "now": "now" does not mean current time. Now is an alias for block.timestamp.
Block.timestamp can be influenced by miners to a certain degree, be careful.`,
location: item.src,
more: 'http://solidity.readthedocs.io/en/develop/frequently-asked-questions.html#are-timestamps-now-block-timestamp-reliable'
}
}).concat(this.warningblockTimestampNodes.map(function (item, i) {
}).concat(this.warningblockTimestampNodes.map((item, i) => {
return {
warning: `use of "block.timestamp": "block.timestamp" can be influenced by miners to a certain degree.
That means that a miner can "choose" the block.timestamp, to a certain degree, to change the outcome of a transaction in the mined block.`,

@ -1,10 +1,10 @@
var name = 'Check effects: '
var desc = 'Avoid potential reentrancy bugs'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var fcallGraph = require('./functionCallGraph')
var AbstractAst = require('./abstractAstView')
var algo = require('./algorithmCategories')
const name = 'Check effects: '
const desc = 'Avoid potential reentrancy bugs'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const fcallGraph = require('./functionCallGraph')
const AbstractAst = require('./abstractAstView')
const algo = require('./algorithmCategories')
function checksEffectsInteraction () {
this.abstractAst = new AbstractAst()
@ -20,10 +20,10 @@ checksEffectsInteraction.prototype.visit = function () { throw new Error('checks
checksEffectsInteraction.prototype.report = function () { throw new Error('checksEffectsInteraction.js no report function set upon construction') }
function report (contracts, multipleContractsWithSameName) {
var warnings = []
var hasModifiers = contracts.some((item) => item.modifiers.length > 0)
const warnings = []
const hasModifiers = contracts.some((item) => item.modifiers.length > 0)
var callGraph = fcallGraph.buildGlobalFuncCallGraph(contracts)
const callGraph = fcallGraph.buildGlobalFuncCallGraph(contracts)
contracts.forEach((contract) => {
contract.functions.forEach((func) => {
@ -33,8 +33,8 @@ function report (contracts, multipleContractsWithSameName) {
contract.functions.forEach((func) => {
if (isPotentialVulnerableFunction(func, getContext(callGraph, contract, func))) {
var funcName = common.getFullQuallyfiedFuncDefinitionIdent(contract.node, func.node, func.parameters)
var comments = (hasModifiers) ? 'Note: Modifiers are currently not considered by this static analysis.' : ''
const funcName = common.getFullQuallyfiedFuncDefinitionIdent(contract.node, func.node, func.parameters)
let comments = (hasModifiers) ? 'Note: Modifiers are currently not considered by this static analysis.' : ''
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}`,
@ -57,8 +57,8 @@ function getStateVariables (contract, func) {
}
function isPotentialVulnerableFunction (func, context) {
var isPotentialVulnerable = false
var interaction = false
let isPotentialVulnerable = false
let interaction = false
func.relevantNodes.forEach((node) => {
if (common.isInteraction(node)) {
interaction = true
@ -71,7 +71,7 @@ function isPotentialVulnerableFunction (func, context) {
function isLocalCallWithStateChange (node, context) {
if (common.isLocalCallGraphRelevantNode(node)) {
var func = fcallGraph.resolveCallGraphSymbol(context.callGraph, common.getFullQualifiedFunctionCallIdent(context.currentContract.node, node))
const func = fcallGraph.resolveCallGraphSymbol(context.callGraph, common.getFullQualifiedFunctionCallIdent(context.currentContract.node, node))
return !func || (func && func.node.changesState)
}
return false

@ -1,10 +1,10 @@
var name = 'Constant functions: '
var desc = 'Check for potentially constant functions'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var fcallGraph = require('./functionCallGraph')
var AbstractAst = require('./abstractAstView')
var algo = require('./algorithmCategories')
const name = 'Constant functions: '
const desc = 'Check for potentially constant functions'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const fcallGraph = require('./functionCallGraph')
const AbstractAst = require('./abstractAstView')
const algo = require('./algorithmCategories')
function constantFunctions () {
this.abstractAst = new AbstractAst()
@ -29,10 +29,10 @@ constantFunctions.prototype.visit = function () { throw new Error('constantFunct
constantFunctions.prototype.report = function () { throw new Error('constantFunctions.js no report function set upon construction') }
function report (contracts, multipleContractsWithSameName) {
var warnings = []
var hasModifiers = contracts.some((item) => item.modifiers.length > 0)
const warnings = []
const hasModifiers = contracts.some((item) => item.modifiers.length > 0)
var callGraph = fcallGraph.buildGlobalFuncCallGraph(contracts)
const callGraph = fcallGraph.buildGlobalFuncCallGraph(contracts)
contracts.forEach((contract) => {
contract.functions.forEach((func) => {
@ -46,8 +46,8 @@ function report (contracts, multipleContractsWithSameName) {
contract.functions.filter((func) => common.hasFunctionBody(func.node)).forEach((func) => {
if (common.isConstantFunction(func.node) !== func.potentiallyshouldBeConst) {
var funcName = common.getFullQuallyfiedFuncDefinitionIdent(contract.node, func.node, func.parameters)
var comments = (hasModifiers) ? 'Note: Modifiers are currently not considered by this static analysis.' : ''
const funcName = common.getFullQuallyfiedFuncDefinitionIdent(contract.node, func.node, func.parameters)
let comments = (hasModifiers) ? 'Note: Modifiers are currently not considered by this static analysis.' : ''
comments += (multipleContractsWithSameName) ? 'Note: Import aliases are currently not supported by this static analysis.' : ''
if (func.potentiallyshouldBeConst) {
warnings.push({
@ -95,7 +95,7 @@ function isConstBreaker (node, context) {
function isCallOnNonConstExternalInterfaceFunction (node, context) {
if (common.isExternalDirectCall(node)) {
var func = fcallGraph.resolveCallGraphSymbol(context.callGraph, common.getFullQualifiedFunctionCallIdent(context.currentContract, node))
const func = fcallGraph.resolveCallGraphSymbol(context.callGraph, common.getFullQualifiedFunctionCallIdent(context.currentContract, node))
return !func || (func && !common.isConstantFunction(func.node.node))
}
return false

@ -1,8 +1,8 @@
var name = 'Delete on dynamic Array: '
var desc = 'Use require and appropriately'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'Delete on dynamic Array: '
const desc = 'Use require and appropriately'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function deleteDynamicArrays () {
this.rel = []

@ -1,7 +1,7 @@
var name = 'Delete from dynamic Array: '
var desc = 'Using delete on an array leaves a gap'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
const name = 'Delete from dynamic Array: '
const desc = 'Using delete on an array leaves a gap'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
function deleteFromDynamicArray () {
this.relevantNodes = []

@ -1,9 +1,9 @@
var name = 'ERC20: '
var desc = 'Decimal should be uint8'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var AbstractAst = require('./abstractAstView')
var algo = require('./algorithmCategories')
const name = 'ERC20: '
const desc = 'Decimal should be uint8'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const AbstractAst = require('./abstractAstView')
const algo = require('./algorithmCategories')
function erc20Decimals () {
this.abstractAst = new AbstractAst()
@ -18,14 +18,14 @@ erc20Decimals.prototype.visit = function () { throw new Error('erc20Decimals.js
erc20Decimals.prototype.report = function () { throw new Error('erc20Decimals.js no report function set upon construction') }
function report (contracts, multipleContractsWithSameName) {
var warnings = []
const warnings = []
contracts.forEach((contract) => {
let contractAbiSignatures = contract.functions.map((f) => common.helpers.buildAbiSignature(common.getFunctionDefinitionName(f.node), f.parameters))
const contractAbiSignatures = contract.functions.map((f) => common.helpers.buildAbiSignature(common.getFunctionDefinitionName(f.node), f.parameters))
if (isERC20(contractAbiSignatures)) {
let decimalsVar = contract.stateVariables.filter((stateVar) => common.getDeclaredVariableName(stateVar) === 'decimals' && (common.getDeclaredVariableType(stateVar) !== 'uint8' || stateVar.attributes.visibility !== 'public'))
let decimalsFun = contract.functions.filter((f) => common.getFunctionDefinitionName(f.node) === 'decimals' &&
const decimalsVar = contract.stateVariables.filter((stateVar) => common.getDeclaredVariableName(stateVar) === 'decimals' && (common.getDeclaredVariableType(stateVar) !== 'uint8' || stateVar.attributes.visibility !== 'public'))
const decimalsFun = contract.functions.filter((f) => common.getFunctionDefinitionName(f.node) === 'decimals' &&
(
(f.returns.length === 0 || f.returns.length > 1) ||
(f.returns.length === 1 && (f.returns[0].type !== 'uint8' || f.node.attributes.visibility !== 'public'))

@ -1,7 +1,7 @@
var name = 'Ether transfer in a loop: '
var desc = 'Avoid transferring Ether to multiple addresses in a loop'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
const name = 'Ether transfer in a loop: '
const desc = 'Avoid transferring Ether to multiple addresses in a loop'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
function etherTransferInLoop () {
this.relevantNodes = []
@ -9,8 +9,8 @@ function etherTransferInLoop () {
etherTransferInLoop.prototype.visit = function (node) {
if (common.isLoop(node)) {
var transferNodes = []
var loopBlockStartIndex = common.getLoopBlockStartIndex(node)
let transferNodes = []
const loopBlockStartIndex = common.getLoopBlockStartIndex(node)
if (common.isBlock(node.children[loopBlockStartIndex])) {
transferNodes = node.children[loopBlockStartIndex].children
.filter(child => (common.isExpressionStatement(child) &&

@ -1,7 +1,7 @@
var name = 'For loop iterates over dynamic array: '
var desc = 'The number of \'for\' loop iterations depends on dynamic array\'s size'
var categories = require('./categories')
var { isForLoop, isDynamicArrayLengthAccess, isBinaryOperation } = require('./staticAnalysisCommon')
const name = 'For loop iterates over dynamic array: '
const desc = 'The number of \'for\' loop iterations depends on dynamic array\'s size'
const categories = require('./categories')
const { isForLoop, isDynamicArrayLengthAccess, isBinaryOperation } = require('./staticAnalysisCommon')
function forLoopIteratesOverDynamicArray () {
this.relevantNodes = []
@ -10,9 +10,9 @@ function forLoopIteratesOverDynamicArray () {
forLoopIteratesOverDynamicArray.prototype.visit = function (node) {
if (isForLoop(node)) {
// Access 'condition' node of 'for' loop statement
let forLoopConditionNode = node.children[1]
const forLoopConditionNode = node.children[1]
// Access right side of condition as its children
let conditionChildrenNode = forLoopConditionNode.children[1]
const conditionChildrenNode = forLoopConditionNode.children[1]
// Check if it is a binary operation. if yes, check if its children node access length of dynamic array
if (isBinaryOperation(conditionChildrenNode) && isDynamicArrayLengthAccess(conditionChildrenNode.children[0])) {
this.relevantNodes.push(node)

@ -1,11 +1,11 @@
'use strict'
var common = require('./staticAnalysisCommon')
const common = require('./staticAnalysisCommon')
function buildLocalFuncCallGraphInternal (functions, nodeFilter, extractNodeIdent, extractFuncDefIdent) {
var callGraph = {}
const callGraph = {}
functions.forEach((func) => {
var calls = func.relevantNodes
const calls = func.relevantNodes
.filter(nodeFilter)
.map(extractNodeIdent)
.filter((name) => name !== extractFuncDefIdent(func)) // filter self recursive call
@ -41,11 +41,11 @@ function buildLocalFuncCallGraphInternal (functions, nodeFilter, extractNodeIden
* @return {map (string -> Contract Call Graph)} returns map from contract name to contract call graph
*/
function buildGlobalFuncCallGraph (contracts) {
var callGraph = {}
const callGraph = {}
contracts.forEach((contract) => {
var filterNodes = (node) => { return common.isLocalCallGraphRelevantNode(node) || common.isExternalDirectCall(node) }
var getNodeIdent = (node) => { return common.getFullQualifiedFunctionCallIdent(contract.node, node) }
var getFunDefIdent = (funcDef) => { return common.getFullQuallyfiedFuncDefinitionIdent(contract.node, funcDef.node, funcDef.parameters) }
const filterNodes = (node) => { return common.isLocalCallGraphRelevantNode(node) || common.isExternalDirectCall(node) }
const getNodeIdent = (node) => { return common.getFullQualifiedFunctionCallIdent(contract.node, node) }
const getFunDefIdent = (funcDef) => { return common.getFullQuallyfiedFuncDefinitionIdent(contract.node, funcDef.node, funcDef.parameters) }
callGraph[common.getContractName(contract.node)] = { contract: contract, functions: buildLocalFuncCallGraphInternal(contract.functions, filterNodes, getNodeIdent, getFunDefIdent) }
})
@ -66,7 +66,7 @@ function analyseCallGraph (callGraph, funcName, context, nodeCheck) {
}
function analyseCallGraphInternal (callGraph, funcName, context, combinator, nodeCheck, visited) {
var current = resolveCallGraphSymbol(callGraph, funcName)
const current = resolveCallGraphSymbol(callGraph, funcName)
if (current === undefined || visited[funcName] === true) return true
visited[funcName] = true
@ -80,20 +80,20 @@ function resolveCallGraphSymbol (callGraph, funcName) {
}
function resolveCallGraphSymbolInternal (callGraph, funcName, silent) {
var current
let current
if (funcName.includes('.')) {
var parts = funcName.split('.')
var contractPart = parts[0]
var functionPart = parts[1]
var currentContract = callGraph[contractPart]
const parts = funcName.split('.')
const contractPart = parts[0]
const functionPart = parts[1]
const currentContract = callGraph[contractPart]
if (!(currentContract === undefined)) {
current = currentContract.functions[funcName]
// resolve inheritance hierarchy
if (current === undefined) {
// resolve inheritance lookup in linearized fashion
var inheritsFromNames = currentContract.contract.inheritsFrom.reverse()
for (var i = 0; i < inheritsFromNames.length; i++) {
var res = resolveCallGraphSymbolInternal(callGraph, inheritsFromNames[i] + '.' + functionPart, true)
const inheritsFromNames = currentContract.contract.inheritsFrom.reverse()
for (let i = 0; i < inheritsFromNames.length; i++) {
const res = resolveCallGraphSymbolInternal(callGraph, inheritsFromNames[i] + '.' + functionPart, true)
if (!(res === undefined)) return res
}
}

@ -1,7 +1,7 @@
var name = 'Gas costs: '
var desc = 'Warn if the gas requirements of functions are too high.'
var categories = require('./categories')
var algo = require('./algorithmCategories')
const name = 'Gas costs: '
const desc = 'Warn if the gas requirements of functions are too high.'
const categories = require('./categories')
const algo = require('./algorithmCategories')
function gasCosts () {
}
@ -13,15 +13,15 @@ function gasCosts () {
*/
// @TODO has been copied from remix-ide repo ! should fix that soon !
function visitContracts (contracts, cb) {
for (var file in contracts) {
for (var name in contracts[file]) {
for (let file in contracts) {
for (let name in contracts[file]) {
if (cb({ name: name, object: contracts[file][name], file: file })) return
}
}
}
gasCosts.prototype.report = function (compilationResults) {
var report = []
const report = []
visitContracts(compilationResults.contracts, (contract) => {
if (
!contract.object.evm.gasEstimates ||
@ -29,7 +29,7 @@ gasCosts.prototype.report = function (compilationResults) {
) {
return
}
var fallback = contract.object.evm.gasEstimates.external['']
const fallback = contract.object.evm.gasEstimates.external['']
if (fallback !== undefined) {
if (fallback === null || fallback >= 2100 || fallback === 'infinite') {
report.push({
@ -43,8 +43,8 @@ gasCosts.prototype.report = function (compilationResults) {
if (functionName === '') {
continue
}
var gas = contract.object.evm.gasEstimates.external[functionName]
var gasString = gas === null ? 'unknown or not constant' : 'high: ' + gas
const gas = contract.object.evm.gasEstimates.external[functionName]
const gasString = gas === null ? 'unknown or not constant' : 'high: ' + gas
if (gas === null || gas >= 3000000 || gas === 'infinite') {
report.push({
warning: `Gas requirement of function ${contract.name}.${functionName} ${gasString}.

@ -1,8 +1,8 @@
var name = 'Guard Conditions: '
var desc = 'Use require and appropriately'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'Guard Conditions: '
const desc = 'Use require and appropriately'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function guardConditions () {
this.guards = []

@ -1,8 +1,8 @@
var name = 'Inline assembly: '
var desc = 'Use of Inline Assembly'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'Inline assembly: '
const desc = 'Use of Inline Assembly'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function inlineAssembly () {
this.inlineAssNodes = []

@ -1,8 +1,8 @@
var name = 'Data Trucated: '
var desc = 'Division on int/uint values truncates the result.'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'Data Trucated: '
const desc = 'Division on int/uint values truncates the result.'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function intDivitionTruncate () {
this.warningNodes = []
@ -13,7 +13,7 @@ intDivitionTruncate.prototype.visit = function (node) {
}
intDivitionTruncate.prototype.report = function (compilationResults) {
return this.warningNodes.map(function (item, i) {
return this.warningNodes.map((item, i) => {
return {
warning: 'Division of integer values yields an integer value again. That means e.g. 10 / 100 = 0 instead of 0.1 since the result is an integer again. This does not hold for division of (only) literal values since those yield rational constants.',
location: item.src

@ -1,8 +1,8 @@
var name = 'Low level calls: '
var desc = 'Semantics maybe unclear'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'Low level calls: '
const desc = 'Semantics maybe unclear'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function lowLevelCalls () {
this.llcNodes = []
@ -27,9 +27,9 @@ lowLevelCalls.prototype.visit = function (node) {
}
lowLevelCalls.prototype.report = function (compilationResults) {
return this.llcNodes.map(function (item, i) {
var text = ''
var morehref = null
return this.llcNodes.map((item, i) => {
let text = ''
let morehref = null
switch (item.type) {
case common.lowLevelCallTypes.CALL:
text = `use of "call": the use of low level "call" should be avoided whenever possible.

@ -1,9 +1,9 @@
var name = 'no return: '
var desc = 'Function with return type is not returning'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var AbstractAst = require('./abstractAstView')
var algo = require('./algorithmCategories')
const name = 'no return: '
const desc = 'Function with return type is not returning'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const AbstractAst = require('./abstractAstView')
const algo = require('./algorithmCategories')
function noReturn () {
this.abstractAst = new AbstractAst()
@ -20,11 +20,11 @@ noReturn.prototype.visit = function () { throw new Error('noReturn.js no visit f
noReturn.prototype.report = function () { throw new Error('noReturn.js no report function set upon construction') }
function report (contracts, multipleContractsWithSameName) {
var warnings = []
const warnings = []
contracts.forEach((contract) => {
contract.functions.filter((func) => common.hasFunctionBody(func.node)).forEach((func) => {
var funcName = common.getFullQuallyfiedFuncDefinitionIdent(contract.node, func.node, func.parameters)
const funcName = common.getFullQuallyfiedFuncDefinitionIdent(contract.node, func.node, func.parameters)
if (hasNamedAndUnnamedReturns(func)) {
warnings.push({
warning: `${funcName}: Mixing of named and unnamed return parameters is not advised.`,
@ -51,9 +51,9 @@ function hasReturnStatement (func) {
}
function hasAssignToAllNamedReturns (func) {
var namedReturns = func.returns.filter((n) => n.name.length > 0).map((n) => n.name)
var assignedVars = func.relevantNodes.filter(common.isAssignment).map(common.getEffectedVariableName)
var diff = namedReturns.filter(e => !assignedVars.includes(e))
const namedReturns = func.returns.filter((n) => n.name.length > 0).map((n) => n.name)
const assignedVars = func.relevantNodes.filter(common.isAssignment).map(common.getEffectedVariableName)
const diff = namedReturns.filter(e => !assignedVars.includes(e))
return diff.length === 0
}

@ -1,9 +1,9 @@
var name = 'Selfdestruct: '
var desc = 'Be aware of caller contracts.'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var AbstractAst = require('./abstractAstView')
var algo = require('./algorithmCategories')
const name = 'Selfdestruct: '
const desc = 'Be aware of caller contracts.'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const AbstractAst = require('./abstractAstView')
const algo = require('./algorithmCategories')
function selfdestruct () {
this.abstractAst = new AbstractAst()
@ -21,7 +21,7 @@ selfdestruct.prototype.visit = function () { throw new Error('selfdestruct.js no
selfdestruct.prototype.report = function () { throw new Error('selfdestruct.js no report function set upon construction') }
function report (contracts, multipleContractsWithSameName) {
var warnings = []
const warnings = []
contracts.forEach((contract) => {
contract.functions.forEach((func) => {

@ -1,12 +1,12 @@
var name = 'Similar variable names: '
var desc = 'Check if variable names are too similar'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var AbstractAst = require('./abstractAstView')
var levenshtein = require('fast-levenshtein')
var remixLib = require('remix-lib')
var util = remixLib.util
var algo = require('./algorithmCategories')
const name = 'Similar variable names: '
const desc = 'Check if variable names are too similar'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const AbstractAst = require('./abstractAstView')
const levenshtein = require('fast-levenshtein')
const remixLib = require('remix-lib')
const util = remixLib.util
const algo = require('./algorithmCategories')
function similarVariableNames () {
this.abstractAst = new AbstractAst()
@ -23,22 +23,22 @@ similarVariableNames.prototype.visit = function () { throw new Error('similarVar
similarVariableNames.prototype.report = function () { throw new Error('similarVariableNames.js no report function set upon construction') }
function report (contracts, multipleContractsWithSameName) {
var warnings = []
var hasModifiers = contracts.some((item) => item.modifiers.length > 0)
const warnings = []
const hasModifiers = contracts.some((item) => item.modifiers.length > 0)
contracts.forEach((contract) => {
contract.functions.forEach((func) => {
var funcName = common.getFullQuallyfiedFuncDefinitionIdent(contract.node, func.node, func.parameters)
var hasModifiersComments = ''
const funcName = common.getFullQuallyfiedFuncDefinitionIdent(contract.node, func.node, func.parameters)
let hasModifiersComments = ''
if (hasModifiers) {
hasModifiersComments = 'Note: Modifiers are currently not considered by this static analysis.'
}
var multipleContractsWithSameNameComments = ''
let multipleContractsWithSameNameComments = ''
if (multipleContractsWithSameName) {
multipleContractsWithSameNameComments = 'Note: Import aliases are currently not supported by this static analysis.'
}
var vars = getFunctionVariables(contract, func).map(common.getDeclaredVariableName)
const vars = getFunctionVariables(contract, func).map(common.getDeclaredVariableName)
findSimilarVarNames(vars).map((sim) => {
warnings.push({
@ -53,12 +53,12 @@ function report (contracts, multipleContractsWithSameName) {
}
function findSimilarVarNames (vars) {
var similar = []
var comb = {}
const similar = []
const comb = {}
vars.map((varName1) => vars.map((varName2) => {
if (varName1.length > 1 && varName2.length > 1 && varName2 !== varName1 && !isCommonPrefixedVersion(varName1, varName2) && !isCommonNrSuffixVersion(varName1, varName2) && !(comb[varName1 + ';' + varName2] || comb[varName2 + ';' + varName1])) {
comb[varName1 + ';' + varName2] = true
var distance = levenshtein.get(varName1, varName2)
const distance = levenshtein.get(varName1, varName2)
if (distance <= 2) similar.push({ var1: varName1, var2: varName2, distance: distance })
}
}))
@ -70,8 +70,7 @@ function isCommonPrefixedVersion (varName1, varName2) {
}
function isCommonNrSuffixVersion (varName1, varName2) {
var ref = '^' + util.escapeRegExp(varName1.slice(0, -1)) + '[0-9]*$'
const ref = '^' + util.escapeRegExp(varName1.slice(0, -1)) + '[0-9]*$'
return varName2.match(ref) != null
}

@ -1,9 +1,9 @@
'use strict'
var remixLib = require('remix-lib')
var util = remixLib.util
const remixLib = require('remix-lib')
const util = remixLib.util
var nodeTypes = {
const nodeTypes = {
IDENTIFIER: 'Identifier',
MEMBERACCESS: 'MemberAccess',
FUNCTIONCALL: 'FunctionCall',
@ -29,7 +29,7 @@ var nodeTypes = {
ELEMENTARYTYPENAMEEXPRESSION: 'ElementaryTypeNameExpression'
}
var basicTypes = {
const basicTypes = {
UINT: 'uint256',
BOOL: 'bool',
ADDRESS: 'address',
@ -40,7 +40,7 @@ var basicTypes = {
BYTES4: 'bytes4'
}
var basicRegex = {
const basicRegex = {
CONTRACTTYPE: '^contract ',
FUNCTIONTYPE: '^function \\(',
EXTERNALFUNCTIONTYPE: '^function \\(.*\\).* external',
@ -50,7 +50,7 @@ var basicRegex = {
LIBRARYTYPE: '^type\\(library (.*)\\)'
}
var basicFunctionTypes = {
const basicFunctionTypes = {
SEND: buildFunctionSignature([basicTypes.UINT], [basicTypes.BOOL], false),
CALL: buildFunctionSignature([], [basicTypes.BOOL], true),
'CALL-v0.5': buildFunctionSignature([basicTypes.BYTES_MEM], [basicTypes.BOOL, basicTypes.BYTES_MEM], true),
@ -59,7 +59,7 @@ var basicFunctionTypes = {
TRANSFER: buildFunctionSignature([basicTypes.UINT], [], false)
}
var builtinFunctions = {
const builtinFunctions = {
'keccak256()': true,
'sha3()': true,
'sha256()': true,
@ -79,7 +79,7 @@ var builtinFunctions = {
'address(address)': true
}
var lowLevelCallTypes = {
const lowLevelCallTypes = {
CALL: { ident: 'call', type: basicFunctionTypes.CALL },
'CALL-v0.5': { ident: 'call', type: basicFunctionTypes['CALL-v0.5'] },
CALLCODE: { ident: 'callcode', type: basicFunctionTypes.CALL },
@ -89,7 +89,7 @@ var lowLevelCallTypes = {
TRANSFER: { ident: 'transfer', type: basicFunctionTypes.TRANSFER }
}
var specialVariables = {
const specialVariables = {
BLOCKTIMESTAMP: { obj: 'block', member: 'timestamp', type: basicTypes.UINT },
BLOCKHASH: {
obj: 'block',
@ -98,7 +98,7 @@ var specialVariables = {
}
}
var abiNamespace = {
const abiNamespace = {
ENCODE: {
obj: 'abi',
member: 'encode',
@ -333,12 +333,12 @@ function getFunctionOrModifierDefinitionReturnParameterPart (funcNode) {
* @return {string} parameter signature
*/
function getFunctionCallTypeParameterType (func) {
var type = getFunctionCallType(func)
const type = getFunctionCallType(func)
if (type.startsWith('function (')) {
var paramTypes = ''
var openPar = 1
for (var x = 10; x < type.length; x++) {
var c = type.charAt(x)
let paramTypes = ''
let openPar = 1
for (let x = 10; x < type.length; x++) {
const c = type.charAt(x)
if (c === '(') openPar++
else if (c === ')') openPar--
@ -1031,7 +1031,7 @@ function nodeType (node, typeRegex) {
}
function name (node, nameRegex) {
var regex = new RegExp(nameRegex)
const regex = new RegExp(nameRegex)
return (node && !nameRegex) || (node && node.attributes && (regex.test(node.attributes.value) || regex.test(node.attributes.member_name)))
}
@ -1046,8 +1046,8 @@ function exactMatch (regexStr) {
}
function matches () {
var args = []
for (var k = 0; k < arguments.length; k++) {
const args = []
for (let k = 0; k < arguments.length; k++) {
args.push(arguments[k])
}
return '(' + args.join('|') + ')'
@ -1078,10 +1078,10 @@ function buildAbiSignature (funName, paramTypes) {
function findFirstSubNodeLTR (node, type) {
if (!node || !node.children) return null
for (let i = 0; i < node.children.length; ++i) {
var item = node.children[i]
const item = node.children[i]
if (nodeType(item, type)) return item
else {
var res = findFirstSubNodeLTR(item, type)
const res = findFirstSubNodeLTR(item, type)
if (res) return res
}
}

@ -1,7 +1,7 @@
var name = 'String Length: '
var desc = 'Bytes length != String length'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
const name = 'String Length: '
const desc = 'Bytes length != String length'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
function stringBytesLength () {
this.stringToBytesConversions = []
@ -31,4 +31,3 @@ module.exports = {
category: categories.MISC,
Module: stringBytesLength
}

@ -1,8 +1,8 @@
var name = 'This on local calls: '
var desc = 'Invocation of local functions via this'
var categories = require('./categories')
var common = require('./staticAnalysisCommon')
var algo = require('./algorithmCategories')
const name = 'This on local calls: '
const desc = 'Invocation of local functions via this'
const categories = require('./categories')
const common = require('./staticAnalysisCommon')
const algo = require('./algorithmCategories')
function thisLocal () {
this.warningNodes = []

@ -1,7 +1,7 @@
var name = 'Transaction origin: '
var desc = 'Warn if tx.origin is used'
var categories = require('./categories')
var algo = require('./algorithmCategories')
const name = 'Transaction origin: '
const desc = 'Warn if tx.origin is used'
const categories = require('./categories')
const algo = require('./algorithmCategories')
function txOrigin () {
this.txOriginNodes = []
@ -19,7 +19,7 @@ txOrigin.prototype.visit = function (node) {
}
txOrigin.prototype.report = function () {
return this.txOriginNodes.map(function (item, i) {
return this.txOriginNodes.map((item, i) => {
return {
warning: `Use of tx.origin: "tx.origin" is useful only in very exceptional cases.
If you use it for authentication, you usually want to replace it by "msg.sender", because otherwise any contract you call can act on your behalf.`,

@ -2561,6 +2561,11 @@
"randomfill": "^1.0.3"
}
},
"crypto-js": {
"version": "3.1.8",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-3.1.8.tgz",
"integrity": "sha1-cV8HC/YBTyrpkqmLOSkli3E/CNU="
},
"d": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/d/-/d-1.0.1.tgz",
@ -3497,6 +3502,38 @@
}
}
},
"ethers": {
"version": "4.0.41",
"resolved": "https://registry.npmjs.org/ethers/-/ethers-4.0.41.tgz",
"integrity": "sha512-QpW2CPZajquwiA7rVDozMksOuvdUBKIruamAakt0++EKBB/VWtLB9zSRZDInLDpp9fZYgOT/0trPD38r6CzLIg==",
"requires": {
"aes-js": "3.0.0",
"bn.js": "^4.4.0",
"elliptic": "6.5.2",
"hash.js": "1.1.3",
"js-sha3": "0.5.7",
"scrypt-js": "2.0.4",
"setimmediate": "1.0.4",
"uuid": "2.0.1",
"xmlhttprequest": "1.8.0"
},
"dependencies": {
"hash.js": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.3.tgz",
"integrity": "sha512-/UETyP0W22QILqS+6HowevwhEFJ3MBJnwTf75Qob9Wz9t0DPuisL8kW8YZMK62dHAKE1c1p+gY1TtOLY+USEHA==",
"requires": {
"inherits": "^2.0.3",
"minimalistic-assert": "^1.0.0"
}
},
"js-sha3": {
"version": "0.5.7",
"resolved": "https://registry.npmjs.org/js-sha3/-/js-sha3-0.5.7.tgz",
"integrity": "sha1-DU/9gALVMzqrr0oj7tL2N0yfKOc="
}
}
},
"ethjs-unit": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/ethjs-unit/-/ethjs-unit-0.1.6.tgz",
@ -3537,6 +3574,11 @@
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-3.1.2.tgz",
"integrity": "sha512-tvtQIeLVHjDkJYnzf2dgVMxfuSGJeM/7UCG17TT4EumTfNtF+0nebF/4zWOIkCreAbtNqhGEboB6BWrwqNaw4Q=="
},
"events": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.0.0.tgz",
"integrity": "sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA=="
},
"evp_bytestokey": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz",
@ -5865,6 +5907,11 @@
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"scrypt-js": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/scrypt-js/-/scrypt-js-2.0.4.tgz",
"integrity": "sha512-4KsaGcPnuhtCZQCxFxN3GVYIhKFPTdLd8PLC552XwbMndtD0cjRFAhDuuydXQ0h08ZfPgzqe6EKHozpuH74iDw=="
},
"scryptsy": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/scryptsy/-/scryptsy-2.1.0.tgz",
@ -7287,6 +7334,11 @@
"xhr-request": "^1.0.1"
}
},
"xhr2": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/xhr2/-/xhr2-0.2.0.tgz",
"integrity": "sha512-BDtiD0i2iKPK/S8OAZfpk6tyzEDnKKSjxWHcMBVmh+LuqJ8A32qXTyOx+TVOg2dKvq6zGBq2sgKPkEeRs1qTRA=="
},
"xhr2-cookies": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/xhr2-cookies/-/xhr2-cookies-1.1.0.tgz",

@ -68,7 +68,7 @@ class DebuggerSolidityState {
}
extractStateVariables (stateVars, address) {
var storageViewer = new StorageViewer({ stepIndex: this.stepManager.currentStepIndex, tx: this.tx, address: address }, this.storageResolver, this.traceManager)
let storageViewer = new StorageViewer({ stepIndex: this.stepManager.currentStepIndex, tx: this.tx, address: address }, this.storageResolver, this.traceManager)
stateDecoder.decodeState(stateVars, storageViewer).then((result) => {
this.event.trigger('solidityStateMessage', [''])
if (result.error) {

@ -1,33 +1,33 @@
'use strict'
var EventManager = require('./src/eventManager')
var traceHelper = require('./src/helpers/traceHelper')
var uiHelper = require('./src/helpers/uiHelper')
var compilerHelper = require('./src/helpers/compilerHelper')
var SourceMappingDecoder = require('./src/sourceMappingDecoder')
var SourceLocationTracker = require('./src/sourceLocationTracker')
var OffsetToColumnConverter = require('./src/offsetToLineColumnConverter')
var init = require('./src/init')
var util = require('./src/util')
var Web3Providers = require('./src/web3Provider/web3Providers')
var DummyProvider = require('./src/web3Provider/dummyProvider')
var Web3VMProvider = require('./src/web3Provider/web3VmProvider')
var AstWalker = require('./src/astWalker')
var Storage = require('./src/storage')
const EventManager = require('./src/eventManager')
const traceHelper = require('./src/helpers/traceHelper')
const uiHelper = require('./src/helpers/uiHelper')
const compilerHelper = require('./src/helpers/compilerHelper')
const SourceMappingDecoder = require('./src/sourceMappingDecoder')
const SourceLocationTracker = require('./src/sourceLocationTracker')
const OffsetToColumnConverter = require('./src/offsetToLineColumnConverter')
const init = require('./src/init')
const util = require('./src/util')
const Web3Providers = require('./src/web3Provider/web3Providers')
const DummyProvider = require('./src/web3Provider/dummyProvider')
const Web3VMProvider = require('./src/web3Provider/web3VmProvider')
const AstWalker = require('./src/astWalker')
const Storage = require('./src/storage')
var EventsDecoder = require('./src/execution/eventsDecoder')
var txExecution = require('./src/execution/txExecution')
var txHelper = require('./src/execution/txHelper')
var txFormat = require('./src/execution/txFormat')
var txListener = require('./src/execution/txListener')
var txRunner = require('./src/execution/txRunner')
var executionContext = require('./src/execution/execution-context')
var typeConversion = require('./src/execution/typeConversion')
const EventsDecoder = require('./src/execution/eventsDecoder')
const txExecution = require('./src/execution/txExecution')
const txHelper = require('./src/execution/txHelper')
const txFormat = require('./src/execution/txFormat')
const txListener = require('./src/execution/txListener')
const txRunner = require('./src/execution/txRunner')
const executionContext = require('./src/execution/execution-context')
const typeConversion = require('./src/execution/typeConversion')
var CodeManager = require('./src/code/codeManager')
var BreakpointManager = require('./src/code/breakpointManager')
var TraceManager = require('./src/trace/traceManager')
const CodeManager = require('./src/code/codeManager')
const BreakpointManager = require('./src/code/breakpointManager')
const TraceManager = require('./src/trace/traceManager')
var UniversalDApp = require('./src/universalDapp')
const UniversalDApp = require('./src/universalDapp')
if (typeof (module) !== 'undefined' && typeof (module.exports) !== 'undefined') {
module.exports = modules()

@ -23,8 +23,8 @@ AstWalker.prototype.walk = function (ast, callback) {
callback['*'] = function () { return true }
}
if (manageCallBack(ast, callback) && ast.children && ast.children.length > 0) {
for (var k in ast.children) {
var child = ast.children[k]
for (let k in ast.children) {
const child = ast.children[k]
this.walk(child, callback)
}
}
@ -37,8 +37,8 @@ AstWalker.prototype.walk = function (ast, callback) {
* @param {Function} - callback used by AstWalker to compute response
*/
AstWalker.prototype.walkAstList = function (sourcesList, callback) {
var walker = new AstWalker()
for (var k in sourcesList) {
const walker = new AstWalker()
for (let k in sourcesList) {
walker.walk(sourcesList[k].legacyAST, callback)
}
}

@ -1,7 +1,7 @@
'use strict'
var EventManager = require('../eventManager')
var helper = require('../helpers/traceHelper')
const EventManager = require('../eventManager')
const helper = require('../helpers/traceHelper')
/**
* allow to manage breakpoint
@ -74,10 +74,10 @@ class BreakpointManager {
}
}
var sourceLocation
var previousSourceLocation
var currentStep = fromStep + direction
var lineHadBreakpoint = false
let sourceLocation
let previousSourceLocation
let currentStep = fromStep + direction
let lineHadBreakpoint = false
while (currentStep > 0 && currentStep < this.debugger.traceManager.trace.length) {
try {
previousSourceLocation = sourceLocation
@ -86,7 +86,7 @@ class BreakpointManager {
console.log('cannot jump to breakpoint ' + e)
return
}
var lineColumn = this.locationToRowConverter(sourceLocation)
let lineColumn = this.locationToRowConverter(sourceLocation)
if (this.previousLine !== lineColumn.start.line) {
if (direction === -1 && lineHadBreakpoint) { // TODO : improve this when we will build the correct structure before hand
lineHadBreakpoint = false
@ -124,11 +124,11 @@ class BreakpointManager {
* @return {Bool} return true if the given @arg fileIndex @arg line refers to a breakpoint
*/
hasBreakpointAtLine (fileIndex, line) {
var filename = this.debugger.solidityProxy.fileNameFromIndex(fileIndex)
const filename = this.debugger.solidityProxy.fileNameFromIndex(fileIndex)
if (filename && this.breakpoints[filename]) {
var sources = this.breakpoints[filename]
for (var k in sources) {
var source = sources[k]
const sources = this.breakpoints[filename]
for (let k in sources) {
const source = sources[k]
if (line === source.row) {
return true
}
@ -143,7 +143,7 @@ class BreakpointManager {
* @return {Bool} true if breapoint registered
*/
hasBreakpoint () {
for (var k in this.breakpoints) {
for (let k in this.breakpoints) {
if (this.breakpoints[k].length) {
return true
}
@ -172,8 +172,8 @@ class BreakpointManager {
remove (sourceLocation) {
if (this.breakpoints[sourceLocation.fileName]) {
var sources = this.breakpoints[sourceLocation.fileName]
for (var k in sources) {
var source = sources[k]
for (let k in sources) {
const source = sources[k]
if (sourceLocation.row === source.row) {
sources.splice(k, 1)
this.event.trigger('breakpointRemoved', [sourceLocation])

@ -1,9 +1,9 @@
'use strict'
var EventManager = require('../eventManager')
var traceHelper = require('../helpers/traceHelper')
var SourceMappingDecoder = require('../sourceMappingDecoder')
var CodeResolver = require('./codeResolver')
const EventManager = require('../eventManager')
const traceHelper = require('../helpers/traceHelper')
const SourceMappingDecoder = require('../sourceMappingDecoder')
const CodeResolver = require('./codeResolver')
/*
resolve contract code referenced by vmtrace in order to be used by asm listview.
@ -36,15 +36,14 @@ CodeManager.prototype.clear = function () {
CodeManager.prototype.resolveStep = function (stepIndex, tx) {
if (stepIndex < 0) return
this.event.trigger('resolvingStep')
var self = this
if (stepIndex === 0) {
retrieveCodeAndTrigger(self, tx.to, stepIndex, tx)
retrieveCodeAndTrigger(this, tx.to, stepIndex, tx)
} else {
this.traceManager.getCurrentCalledAddressAt(stepIndex, function (error, address) {
this.traceManager.getCurrentCalledAddressAt(stepIndex, (error, address) => {
if (error) {
console.log(error)
} else {
retrieveCodeAndTrigger(self, address, stepIndex, tx)
retrieveCodeAndTrigger(this, address, stepIndex, tx)
}
})
}
@ -57,13 +56,12 @@ CodeManager.prototype.resolveStep = function (stepIndex, tx) {
* @param {Function} cb - callback function, return the bytecode
*/
CodeManager.prototype.getCode = function (address, cb) {
const self = this
if (traceHelper.isContractCreation(address)) {
var codes = this.codeResolver.getExecutingCodeFromCache(address)
if (!codes) {
this.traceManager.getContractCreationCode(address, function (error, hexCode) {
this.traceManager.getContractCreationCode(address, (error, hexCode) => {
if (!error) {
codes = self.codeResolver.cacheExecutingCode(address, hexCode)
codes = this.codeResolver.cacheExecutingCode(address, hexCode)
cb(null, codes)
}
})
@ -71,7 +69,7 @@ CodeManager.prototype.getCode = function (address, cb) {
cb(null, codes)
}
} else {
this.codeResolver.resolveCode(address, function (address, code) {
this.codeResolver.resolveCode(address, (address, code) => {
cb(null, code)
})
}
@ -86,18 +84,17 @@ CodeManager.prototype.getCode = function (address, cb) {
* @return {Object} return the ast node of the function
*/
CodeManager.prototype.getFunctionFromStep = function (stepIndex, sourceMap, ast) {
var self = this
this.traceManager.getCurrentCalledAddressAt(stepIndex, function (error, address) {
this.traceManager.getCurrentCalledAddressAt(stepIndex, (error, address) => {
if (error) {
console.log(error)
return { error: 'Cannot retrieve current address for ' + stepIndex }
} else {
self.traceManager.getCurrentPC(stepIndex, function (error, pc) {
this.traceManager.getCurrentPC(stepIndex, (error, pc) => {
if (error) {
console.log(error)
return { error: 'Cannot retrieve current PC for ' + stepIndex }
} else {
return self.getFunctionFromPC(address, pc, sourceMap, ast)
return this.getFunctionFromPC(address, pc, sourceMap, ast)
}
})
}
@ -112,13 +109,12 @@ CodeManager.prototype.getFunctionFromStep = function (stepIndex, sourceMap, ast)
* @param {Function} callback - instruction index
*/
CodeManager.prototype.getInstructionIndex = function (address, step, callback) {
const self = this
this.traceManager.getCurrentPC(step, function (error, pc) {
this.traceManager.getCurrentPC(step, (error, pc) => {
if (error) {
console.log(error)
callback('Cannot retrieve current PC for ' + step, null)
} else {
var itemIndex = self.codeResolver.getInstructionIndex(address, pc)
const itemIndex = this.codeResolver.getInstructionIndex(address, pc)
callback(null, itemIndex)
}
})
@ -134,12 +130,12 @@ CodeManager.prototype.getInstructionIndex = function (address, step, callback) {
* @return {Object} return the ast node of the function
*/
CodeManager.prototype.getFunctionFromPC = function (address, pc, sourceMap, ast) {
var instIndex = this.codeResolver.getInstructionIndex(address, pc)
const instIndex = this.codeResolver.getInstructionIndex(address, pc)
return SourceMappingDecoder.findNodeAtInstructionIndex('FunctionDefinition', instIndex, sourceMap, ast)
}
function retrieveCodeAndTrigger (codeMananger, address, stepIndex, tx) {
codeMananger.getCode(address, function (error, result) {
codeMananger.getCode(address, (error, result) => {
if (!error) {
retrieveIndexAndTrigger(codeMananger, address, stepIndex, result.instructions)
} else {
@ -149,7 +145,7 @@ function retrieveCodeAndTrigger (codeMananger, address, stepIndex, tx) {
}
function retrieveIndexAndTrigger (codeMananger, address, step, code) {
codeMananger.getInstructionIndex(address, step, function (error, result) {
codeMananger.getInstructionIndex(address, step, (error, result) => {
if (!error) {
codeMananger.event.trigger('changed', [code, address, result])
} else {

@ -1,5 +1,5 @@
'use strict'
var codeUtils = require('./codeUtils')
const codeUtils = require('./codeUtils')
function CodeResolver (options) {
this.web3 = options.web3
@ -16,20 +16,18 @@ CodeResolver.prototype.clear = function () {
}
CodeResolver.prototype.resolveCode = function (address, callBack) {
var cache = this.getExecutingCodeFromCache(address)
const cache = this.getExecutingCodeFromCache(address)
if (cache) {
callBack(address, cache)
return
return callBack(address, cache)
}
var self = this
this.loadCode(address, function (code) {
callBack(address, self.cacheExecutingCode(address, code))
this.loadCode(address, (code) => {
callBack(address, this.cacheExecutingCode(address, code))
})
}
CodeResolver.prototype.loadCode = function (address, callback) {
this.web3.eth.getCode(address, function (error, result) {
this.web3.eth.getCode(address, (error, result) => {
if (error) {
console.log(error)
} else {
@ -39,7 +37,7 @@ CodeResolver.prototype.loadCode = function (address, callback) {
}
CodeResolver.prototype.cacheExecutingCode = function (address, hexCode) {
var codes = this.formatCode(hexCode)
const codes = this.formatCode(hexCode)
this.bytecodeByAddress[address] = hexCode
this.instructionsByAddress[address] = codes.code
this.instructionsIndexByBytesOffset[address] = codes.instructionsIndexByBytesOffset
@ -47,7 +45,7 @@ CodeResolver.prototype.cacheExecutingCode = function (address, hexCode) {
}
CodeResolver.prototype.formatCode = function (hexCode) {
var code = codeUtils.nameOpCodes(Buffer.from(hexCode.substring(2), 'hex'))
const code = codeUtils.nameOpCodes(Buffer.from(hexCode.substring(2), 'hex'))
return {
code: code[0],
instructionsIndexByBytesOffset: code[1]
@ -61,9 +59,8 @@ CodeResolver.prototype.getExecutingCodeFromCache = function (address) {
instructionsIndexByBytesOffset: this.instructionsIndexByBytesOffset[address],
bytecode: this.bytecodeByAddress[address]
}
} else {
return null
}
return null
}
CodeResolver.prototype.getInstructionIndex = function (address, pc) {

@ -1,24 +1,24 @@
'use strict'
var opcodes = require('./opcodes')
const opcodes = require('./opcodes')
module.exports = {
nameOpCodes: function (raw) {
var pushData = ''
var codeMap = {}
var code = []
let pushData = ''
const codeMap = {}
const code = []
for (var i = 0; i < raw.length; i++) {
var pc = i
var curOpCode = opcodes(raw[pc], false).name
for (let i = 0; i < raw.length; i++) {
const pc = i
const curOpCode = opcodes(raw[pc], false).name
codeMap[i] = code.length
// no destinations into the middle of PUSH
if (curOpCode.slice(0, 4) === 'PUSH') {
var jumpNum = raw[pc] - 0x5f
const jumpNum = raw[pc] - 0x5f
pushData = raw.slice(pc + 1, pc + jumpNum + 1)
i += jumpNum
}
var data = pushData.toString('hex') !== '' ? ' ' + pushData.toString('hex') : ''
const data = pushData.toString('hex') !== '' ? ' ' + pushData.toString('hex') : ''
code.push(this.pad(pc, this.roundLog(raw.length, 10)) + ' ' + curOpCode + data)
pushData = ''
@ -31,15 +31,15 @@ module.exports = {
* information about the opcode.
*/
parseCode: function (raw) {
var code = []
for (var i = 0; i < raw.length; i++) {
var opcode = opcodes(raw[i], true)
const code = []
for (let i = 0; i < raw.length; i++) {
const opcode = opcodes(raw[i], true)
if (opcode.name.slice(0, 4) === 'PUSH') {
var length = raw[i] - 0x5f
const length = raw[i] - 0x5f
opcode.pushData = raw.slice(i + 1, i + length + 1)
// in case pushdata extends beyond code
if (i + 1 + length > raw.length) {
for (var j = opcode.pushData.length; j < length; j++) {
for (let j = opcode.pushData.length; j < length; j++) {
opcode.pushData.push(0)
}
}
@ -51,7 +51,7 @@ module.exports = {
},
pad: function (num, size) {
var s = num + ''
let s = num + ''
while (s.length < size) s = '0' + s
return s
},

@ -1,22 +1,22 @@
'use strict'
var parseCode = require('./codeUtils').parseCode
var util = require('../util')
const parseCode = require('./codeUtils').parseCode
const util = require('../util')
var createExpressions = function (instructions) {
var expressions = []
var labels = 0
for (var i = 0; i < instructions.length; i++) {
var expr = instructions[i]
const createExpressions = function (instructions) {
const expressions = []
let labels = 0
for (let i = 0; i < instructions.length; i++) {
const expr = instructions[i]
expr.functional = false
if (expr.name === 'JUMPDEST') {
expr.label = 'label' + (++labels)
} else if (expr.name.slice(0, 3) === 'DUP') {
} else if (expr.name.slice(0, 4) === 'SWAP') {
} else if (expr.out <= 1 && expr.in <= expressions.length) {
var error = false
for (var j = 0; j < expr.in && !error; j++) {
var arg = expressions[expressions.length - j - 1]
let error = false
for (let j = 0; j < expr.in && !error; j++) {
const arg = expressions[expressions.length - j - 1]
if (!arg.functional || arg.out !== 1) {
error = true
break
@ -32,7 +32,7 @@ var createExpressions = function (instructions) {
return expressions
}
var toString = function (expr) {
const toString = function (expr) {
if (expr.name.slice(0, 4) === 'PUSH') {
return util.hexConvert(expr.pushData)
} else if (expr.name === 'JUMPDEST') {
@ -44,8 +44,8 @@ var toString = function (expr) {
}
}
var disassemble = function (input) {
var code = parseCode(util.hexToIntArray(input))
const disassemble = function (input) {
const code = parseCode(util.hexToIntArray(input))
return createExpressions(code).map(toString).join('\n')
}

@ -1,5 +1,5 @@
'use strict'
var codes = {
const codes = {
// 0x0 range - arithmetic ops
// name, baseCost, off stack, on stack, dynamic, async
// @todo can be improved on basis of this: https://github.com/ethereumjs/ethereumjs-vm/blob/master/lib/evm/opcodes.ts
@ -168,8 +168,8 @@ var codes = {
}
module.exports = function (op, full) {
var code = codes[op] ? codes[op] : ['INVALID', 0, 0, 0, false, false]
var opcode = code[0]
const code = codes[op] ? codes[op] : ['INVALID', 0, 0, 0, false, false]
let opcode = code[0]
if (full) {
if (opcode === 'LOG') {

@ -21,7 +21,7 @@ eventManager.prototype.unregister = function (eventName, obj, func) {
func = obj
obj = this.anonymous
}
for (var reg in this.registered[eventName]) {
for (let reg in this.registered[eventName]) {
if (this.registered[eventName][reg].obj === obj && this.registered[eventName][reg].func === func) {
this.registered[eventName].splice(reg, 1)
}
@ -61,8 +61,8 @@ eventManager.prototype.trigger = function (eventName, args) {
if (!this.registered[eventName]) {
return
}
for (var listener in this.registered[eventName]) {
var l = this.registered[eventName][listener]
for (let listener in this.registered[eventName]) {
const l = this.registered[eventName][listener]
l.func.apply(l.obj === this.anonymous ? {} : l.obj, args)
}
}

@ -1,6 +1,6 @@
'use strict'
var ethers = require('ethers')
var txHelper = require('./txHelper')
const ethers = require('ethers')
const txHelper = require('./txHelper')
/**
* Register to txListener and extract events
@ -37,17 +37,17 @@ class EventsDecoder {
}
_eventABI (contract) {
var eventABI = {}
var abi = new ethers.utils.Interface(contract.abi)
for (var e in abi.events) {
var event = abi.events[e]
const eventABI = {}
const abi = new ethers.utils.Interface(contract.abi)
for (let e in abi.events) {
const event = abi.events[e]
eventABI[event.topic.replace('0x', '')] = { event: event.name, inputs: event.inputs, object: event, abi: abi }
}
return eventABI
}
_eventsABI (compiledContracts) {
var eventsABI = {}
const eventsABI = {}
txHelper.visitContracts(compiledContracts, (contract) => {
eventsABI[contract.name] = this._eventABI(contract.object)
})
@ -55,7 +55,7 @@ class EventsDecoder {
}
_event (hash, eventsABI) {
for (var k in eventsABI) {
for (let k in eventsABI) {
if (eventsABI[k][hash]) {
return eventsABI[k][hash]
}
@ -79,16 +79,16 @@ class EventsDecoder {
}
_decodeEvents (tx, logs, contractName, compiledContracts, cb) {
var eventsABI = this._eventsABI(compiledContracts)
var events = []
for (var i in logs) {
const eventsABI = this._eventsABI(compiledContracts)
const events = []
for (let i in logs) {
// [address, topics, mem]
var log = logs[i]
var topicId = log.topics[0]
var eventAbi = this._event(topicId.replace('0x', ''), eventsABI)
const log = logs[i]
const topicId = log.topics[0]
const eventAbi = this._event(topicId.replace('0x', ''), eventsABI)
if (eventAbi) {
var decodedlog = eventAbi.abi.parseLog(log)
let decoded = {}
const decodedlog = eventAbi.abi.parseLog(log)
const decoded = {}
for (const v in decodedlog.values) {
decoded[v] = this._stringifyEvent(decodedlog.values[v])
}

@ -11,9 +11,10 @@ const LogsManager = require('./logsManager.js')
const rlp = ethUtil.rlp
let web3
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
var injectedProvider = window.web3.currentProvider
var web3 = new Web3(injectedProvider)
web3 = new Web3(injectedProvider)
} else {
web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
}
@ -36,17 +37,16 @@ class StateManagerCommonStorageDump extends StateManager {
}
dumpStorage (address, cb) {
var self = this
this._getStorageTrie(address, function (err, trie) {
this._getStorageTrie(address, (err, trie) => {
if (err) {
return cb(err)
}
var storage = {}
var stream = trie.createReadStream()
stream.on('data', function (val) {
var value = rlp.decode(val.value)
const storage = {}
const stream = trie.createReadStream()
stream.on('data', (val) => {
const value = rlp.decode(val.value)
storage['0x' + val.key.toString('hex')] = {
key: self.keyHashes[val.key.toString('hex')],
key: this.keyHashes[val.key.toString('hex')],
value: '0x' + value.toString('hex')
}
})
@ -57,7 +57,7 @@ class StateManagerCommonStorageDump extends StateManager {
}
getStateRoot (cb) {
let checkpoint = this._checkpointCount
const checkpoint = this._checkpointCount
this._checkpointCount = 0
super.getStateRoot((err, stateRoot) => {
this._checkpointCount = checkpoint
@ -76,39 +76,38 @@ class StateManagerCommonStorageDump extends StateManager {
}
function createVm (hardfork) {
var stateManager = new StateManagerCommonStorageDump({})
const stateManager = new StateManagerCommonStorageDump({})
stateManager.checkpoint(() => {})
var vm = new EthJSVM({
const vm = new EthJSVM({
activatePrecompiles: true,
blockchain: stateManager.blockchain,
stateManager: stateManager,
hardfork: hardfork
})
vm.blockchain.validate = false
var web3vm = new Web3VMProvider()
const web3vm = new Web3VMProvider()
web3vm.setVM(vm)
return { vm, web3vm, stateManager }
}
var vms = {
const vms = {
byzantium: createVm('byzantium'),
constantinople: createVm('constantinople'),
petersburg: createVm('petersburg'),
istanbul: createVm('istanbul')
}
var mainNetGenesisHash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3'
const mainNetGenesisHash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3'
/*
trigger contextChanged, web3EndpointChanged
*/
function ExecutionContext () {
var self = this
this.event = new EventManager()
this.logsManager = new LogsManager()
var executionContext = null
let executionContext = null
this.blockGasLimitDefault = 4300000
this.blockGasLimit = this.blockGasLimitDefault
@ -148,7 +147,7 @@ function ExecutionContext () {
callback(null, { id: '-', name: 'VM' })
} else {
web3.eth.net.getId((err, id) => {
var name = null
let name = null
if (err) name = 'Unknown'
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
else if (id === 1) name = 'Main'
@ -172,38 +171,38 @@ function ExecutionContext () {
}
}
this.removeProvider = function (name) {
this.removeProvider = (name) => {
if (name && this.customNetWorks[name]) {
delete this.customNetWorks[name]
self.event.trigger('removeProvider', [name])
this.event.trigger('removeProvider', [name])
}
}
this.addProvider = function (network) {
this.addProvider = (network) => {
if (network && network.name && network.url) {
this.customNetWorks[network.name] = network
self.event.trigger('addProvider', [network])
this.event.trigger('addProvider', [network])
}
}
this.internalWeb3 = function () {
this.internalWeb3 = () => {
return web3
}
this.blankWeb3 = function () {
this.blankWeb3 = () => {
return blankWeb3
}
this.vm = function () {
this.vm = () => {
return vms[currentFork].vm
}
this.setContext = function (context, endPointUrl, confirmCb, infoCb) {
this.setContext = (context, endPointUrl, confirmCb, infoCb) => {
executionContext = context
this.executionContextChange(context, endPointUrl, confirmCb, infoCb)
}
this.executionContextChange = function (context, endPointUrl, confirmCb, infoCb, cb) {
this.executionContextChange = (context, endPointUrl, confirmCb, infoCb, cb) => {
if (!cb) cb = () => {}
if (context === 'vm') {
@ -211,7 +210,7 @@ function ExecutionContext () {
vms[currentFork].stateManager.revert(() => {
vms[currentFork].stateManager.checkpoint(() => {})
})
self.event.trigger('contextChanged', ['vm'])
this.event.trigger('contextChanged', ['vm'])
return cb()
}
@ -220,11 +219,11 @@ function ExecutionContext () {
infoCb('No injected Web3 provider found. Make sure your provider (e.g. MetaMask) is active and running (when recently activated you may have to reload the page).')
return cb()
} else {
self.askPermission()
this.askPermission()
executionContext = context
web3.setProvider(injectedProvider)
self._updateBlockGasLimit()
self.event.trigger('contextChanged', ['injected'])
this._updateBlockGasLimit()
this.event.trigger('contextChanged', ['injected'])
return cb()
}
}
@ -239,16 +238,16 @@ function ExecutionContext () {
}
}
this.currentblockGasLimit = function () {
this.currentblockGasLimit = () => {
return this.blockGasLimit
}
this.stopListenOnLastBlock = function () {
this.stopListenOnLastBlock = () => {
if (this.listenOnLastBlockId) clearInterval(this.listenOnLastBlockId)
this.listenOnLastBlockId = null
}
this._updateBlockGasLimit = function () {
this._updateBlockGasLimit = () => {
if (this.getProvider() !== 'vm') {
web3.eth.getBlock('latest', (err, block) => {
if (!err) {
@ -261,15 +260,17 @@ function ExecutionContext () {
}
}
this.listenOnLastBlock = function () {
this.listenOnLastBlock = () => {
this.listenOnLastBlockId = setInterval(() => {
this._updateBlockGasLimit()
}, 15000)
}
// TODO: remove this when this function is moved
const self = this
// TODO: not used here anymore and needs to be moved
function setProviderFromEndpoint (endpoint, context, cb) {
var oldProvider = web3.currentProvider
const oldProvider = web3.currentProvider
if (endpoint === 'ipc') {
web3.setProvider(new web3.providers.IpcProvider())
@ -291,32 +292,32 @@ function ExecutionContext () {
}
this.setProviderFromEndpoint = setProviderFromEndpoint
this.txDetailsLink = function (network, hash) {
this.txDetailsLink = (network, hash) => {
if (transactionDetailsLinks[network]) {
return transactionDetailsLinks[network] + hash
}
}
this.addBlock = function (block) {
this.addBlock = (block) => {
let blockNumber = '0x' + block.header.number.toString('hex')
if (blockNumber === '0x') {
blockNumber = '0x0'
}
blockNumber = web3.utils.toHex(web3.utils.toBN(blockNumber))
self.blocks['0x' + block.hash().toString('hex')] = block
self.blocks[blockNumber] = block
self.latestBlockNumber = blockNumber
this.blocks['0x' + block.hash().toString('hex')] = block
this.blocks[blockNumber] = block
this.latestBlockNumber = blockNumber
this.logsManager.checkBlock(blockNumber, block, this.web3())
}
this.trackTx = function (tx, block) {
self.txs[tx] = block
this.trackTx = (tx, block) => {
this.txs[tx] = block
}
}
var transactionDetailsLinks = {
const transactionDetailsLinks = {
'Main': 'https://www.etherscan.io/tx/',
'Rinkeby': 'https://rinkeby.etherscan.io/tx/',
'Ropsten': 'https://ropsten.etherscan.io/tx/',

@ -71,7 +71,7 @@ module.exports = {
STOP: 'stop',
REFUND_EXHAUSTED: 'refund exhausted'
}
let ret = {
const ret = {
error: false,
message: ''
}

@ -1,9 +1,9 @@
'use strict'
var ethers = require('ethers')
var helper = require('./txHelper')
var asyncJS = require('async')
var solcLinker = require('solc/linker')
var ethJSUtil = require('ethereumjs-util')
const ethers = require('ethers')
const helper = require('./txHelper')
const asyncJS = require('async')
const solcLinker = require('solc/linker')
const ethJSUtil = require('ethereumjs-util')
module.exports = {
@ -15,8 +15,8 @@ module.exports = {
* @param {String} contractbyteCode
*/
encodeData: function (funABI, values, contractbyteCode) {
var encoded
var encodedHex
let encoded
let encodedHex
try {
encoded = helper.encodeParams(funABI, values)
encodedHex = encoded.toString('hex')
@ -38,9 +38,9 @@ module.exports = {
* @param {Function} callback - callback
*/
encodeParams: function (params, funAbi, callback) {
var data = ''
var dataHex = ''
var funArgs
let data = ''
let dataHex = ''
let funArgs
if (params.indexOf('raw:0x') === 0) {
// in that case we consider that the input is already encoded and *does not* contain the method signature
dataHex = params.replace('raw:0x', '')
@ -51,16 +51,14 @@ module.exports = {
params = params.replace(/(^|,\s+|,)(0[xX][0-9a-fA-F]+)(\s+,|,|$)/g, '$1"$2"$3') // replace non quoted hex string by quoted hex string
funArgs = JSON.parse('[' + params + ']')
} catch (e) {
callback('Error encoding arguments: ' + e)
return
return callback('Error encoding arguments: ' + e)
}
if (funArgs.length > 0) {
try {
data = helper.encodeParams(funAbi, funArgs)
dataHex = data.toString('hex')
} catch (e) {
callback('Error encoding arguments: ' + e)
return
return callback('Error encoding arguments: ' + e)
}
}
if (data.slice(0, 9) === 'undefined') {
@ -100,12 +98,12 @@ module.exports = {
encodeConstructorCallAndLinkLibraries: function (contract, params, funAbi, linkLibraries, linkReferences, callback) {
this.encodeParams(params, funAbi, (error, encodedParam) => {
if (error) return callback(error)
var bytecodeToDeploy = contract.evm.bytecode.object
let bytecodeToDeploy = contract.evm.bytecode.object
if (bytecodeToDeploy.indexOf('_') >= 0) {
if (linkLibraries && linkReferences) {
for (var libFile in linkLibraries) {
for (var lib in linkLibraries[libFile]) {
var address = linkLibraries[libFile][lib]
for (let libFile in linkLibraries) {
for (let lib in linkLibraries[libFile]) {
const address = linkLibraries[libFile][lib]
if (!ethJSUtil.isValidAddress(address)) return callback(address + ' is not a valid address. Please check the provided address is valid.')
bytecodeToDeploy = this.linkLibraryStandardFromlinkReferences(lib, address.replace('0x', ''), bytecodeToDeploy, linkReferences)
}
@ -135,9 +133,9 @@ module.exports = {
encodeConstructorCallAndDeployLibraries: function (contractName, contract, contracts, params, funAbi, callback, callbackStep, callbackDeployLibrary) {
this.encodeParams(params, funAbi, (error, encodedParam) => {
if (error) return callback(error)
var dataHex = ''
var contractBytecode = contract.evm.bytecode.object
var bytecodeToDeploy = contract.evm.bytecode.object
let dataHex = ''
const contractBytecode = contract.evm.bytecode.object
let bytecodeToDeploy = contract.evm.bytecode.object
if (bytecodeToDeploy.indexOf('_') >= 0) {
this.linkBytecode(contract, contracts, (err, bytecode) => {
if (err) {
@ -169,9 +167,9 @@ module.exports = {
* @param {Function} callbackDeployLibrary - callbackDeployLibrary
*/
buildData: function (contractName, contract, contracts, isConstructor, funAbi, params, callback, callbackStep, callbackDeployLibrary) {
var funArgs = []
var data = ''
var dataHex = ''
let funArgs = []
let data = ''
let dataHex = ''
if (params.indexOf('raw:0x') === 0) {
// in that case we consider that the input is already encoded and *does not* contain the method signature
@ -183,15 +181,13 @@ module.exports = {
funArgs = this.parseFunctionParams(params)
}
} catch (e) {
callback('Error encoding arguments: ' + e)
return
return callback('Error encoding arguments: ' + e)
}
try {
data = helper.encodeParams(funAbi, funArgs)
dataHex = data.toString('hex')
} catch (e) {
callback('Error encoding arguments: ' + e)
return
return callback('Error encoding arguments: ' + e)
}
if (data.slice(0, 9) === 'undefined') {
dataHex = data.slice(9)
@ -200,10 +196,10 @@ module.exports = {
dataHex = data.slice(2)
}
}
var contractBytecode
let contractBytecode
if (isConstructor) {
contractBytecode = contract.evm.bytecode.object
var bytecodeToDeploy = contract.evm.bytecode.object
let bytecodeToDeploy = contract.evm.bytecode.object
if (bytecodeToDeploy.indexOf('_') >= 0) {
this.linkBytecode(contract, contracts, (err, bytecode) => {
if (err) {
@ -226,16 +222,16 @@ module.exports = {
atAddress: function () {},
linkBytecodeStandard: function (contract, contracts, callback, callbackStep, callbackDeployLibrary) {
var contractBytecode = contract.evm.bytecode.object
let contractBytecode = contract.evm.bytecode.object
asyncJS.eachOfSeries(contract.evm.bytecode.linkReferences, (libs, file, cbFile) => {
asyncJS.eachOfSeries(contract.evm.bytecode.linkReferences[file], (libRef, libName, cbLibDeployed) => {
var library = contracts[file][libName]
const library = contracts[file][libName]
if (library) {
this.deployLibrary(file + ':' + libName, libName, library, contracts, (error, address) => {
if (error) {
return cbLibDeployed(error)
}
var hexAddress = address.toString('hex')
let hexAddress = address.toString('hex')
if (hexAddress.slice(0, 2) === '0x') {
hexAddress = hexAddress.slice(2)
}
@ -257,21 +253,21 @@ module.exports = {
},
linkBytecodeLegacy: function (contract, contracts, callback, callbackStep, callbackDeployLibrary) {
var libraryRefMatch = contract.evm.bytecode.object.match(/__([^_]{1,36})__/)
const libraryRefMatch = contract.evm.bytecode.object.match(/__([^_]{1,36})__/)
if (!libraryRefMatch) {
return callback('Invalid bytecode format.')
}
var libraryName = libraryRefMatch[1]
const libraryName = libraryRefMatch[1]
// file_name:library_name
var libRef = libraryName.match(/(.*):(.*)/)
const libRef = libraryName.match(/(.*):(.*)/)
if (!libRef) {
return callback('Cannot extract library reference ' + libraryName)
}
if (!contracts[libRef[1]] || !contracts[libRef[1]][libRef[2]]) {
return callback('Cannot find library reference ' + libraryName)
}
var libraryShortName = libRef[2]
var library = contracts[libRef[1]][libraryShortName]
const libraryShortName = libRef[2]
const library = contracts[libRef[1]][libraryShortName]
if (!library) {
return callback('Library ' + libraryName + ' not found.')
}
@ -279,7 +275,7 @@ module.exports = {
if (err) {
return callback(err)
}
var hexAddress = address.toString('hex')
let hexAddress = address.toString('hex')
if (hexAddress.slice(0, 2) === '0x') {
hexAddress = hexAddress.slice(2)
}
@ -300,11 +296,11 @@ module.exports = {
},
deployLibrary: function (libraryName, libraryShortName, library, contracts, callback, callbackStep, callbackDeployLibrary) {
var address = library.address
const address = library.address
if (address) {
return callback(null, address)
}
var bytecode = library.evm.bytecode.object
const bytecode = library.evm.bytecode.object
if (bytecode.indexOf('_') >= 0) {
this.linkBytecode(library, contracts, (err, bytecode) => {
if (err) callback(err)
@ -315,12 +311,12 @@ module.exports = {
}, callbackStep, callbackDeployLibrary)
} else {
callbackStep(`creation of library ${libraryName} pending...`)
var data = {dataHex: bytecode, funAbi: {type: 'constructor'}, funArgs: [], contractBytecode: bytecode, contractName: libraryShortName}
const data = {dataHex: bytecode, funAbi: {type: 'constructor'}, funArgs: [], contractBytecode: bytecode, contractName: libraryShortName}
callbackDeployLibrary({ data: data, useCall: false }, (err, txResult) => {
if (err) {
return callback(err)
}
var address = txResult.result.createdAddress || txResult.result.contractAddress
const address = txResult.result.createdAddress || txResult.result.contractAddress
library.address = address
callback(err, address)
})
@ -328,8 +324,8 @@ module.exports = {
},
linkLibraryStandardFromlinkReferences: function (libraryName, address, bytecode, linkReferences) {
for (var file in linkReferences) {
for (var libName in linkReferences[file]) {
for (let file in linkReferences) {
for (let libName in linkReferences[file]) {
if (libraryName === libName) {
bytecode = this.setLibraryAddress(address, bytecode, linkReferences[file][libName])
}
@ -344,8 +340,8 @@ module.exports = {
setLibraryAddress: function (address, bytecodeToLink, positions) {
if (positions) {
for (var pos of positions) {
var regpos = bytecodeToLink.match(new RegExp(`(.{${2 * pos.start}})(.{${2 * pos.length}})(.*)`))
for (let pos of positions) {
const regpos = bytecodeToLink.match(new RegExp(`(.{${2 * pos.start}})(.{${2 * pos.length}})(.*)`))
if (regpos) {
bytecodeToLink = regpos[1] + address + regpos[3]
}
@ -362,22 +358,22 @@ module.exports = {
// Only decode if there supposed to be fields
if (fnabi.outputs && fnabi.outputs.length > 0) {
try {
var i
let i
var outputTypes = []
const outputTypes = []
for (i = 0; i < fnabi.outputs.length; i++) {
var type = fnabi.outputs[i].type
const type = fnabi.outputs[i].type
outputTypes.push(type.indexOf('tuple') === 0 ? helper.makeFullTypeDefinition(fnabi.outputs[i]) : type)
}
if (!response.length) response = new Uint8Array(32 * fnabi.outputs.length) // ensuring the data is at least filled by 0 cause `AbiCoder` throws if there's not engouh data
// decode data
var abiCoder = new ethers.utils.AbiCoder()
var decodedObj = abiCoder.decode(outputTypes, response)
const abiCoder = new ethers.utils.AbiCoder()
const decodedObj = abiCoder.decode(outputTypes, response)
var json = {}
const json = {}
for (i = 0; i < outputTypes.length; i++) {
var name = fnabi.outputs[i].name
const name = fnabi.outputs[i].name
json[i] = outputTypes[i] + ': ' + (name ? name + ' ' + decodedObj[i] : decodedObj[i])
}

@ -1,20 +1,20 @@
'use strict'
var ethers = require('ethers')
const ethers = require('ethers')
module.exports = {
makeFullTypeDefinition: function (typeDef) {
if (typeDef && typeDef.type.indexOf('tuple') === 0 && typeDef.components) {
var innerTypes = typeDef.components.map((innerType) => { return this.makeFullTypeDefinition(innerType) })
const innerTypes = typeDef.components.map((innerType) => { return this.makeFullTypeDefinition(innerType) })
return `tuple(${innerTypes.join(',')})${this.extractSize(typeDef.type)}`
}
return typeDef.type
},
encodeParams: function (funABI, args) {
var types = []
const types = []
if (funABI.inputs && funABI.inputs.length) {
for (var i = 0; i < funABI.inputs.length; i++) {
var type = funABI.inputs[i].type
for (let i = 0; i < funABI.inputs.length; i++) {
const type = funABI.inputs[i].type
// "false" will be converting to `false` and "true" will be working
// fine as abiCoder assume anything in quotes as `true`
if (type === 'bool' && args[i] === 'false') {
@ -29,13 +29,13 @@ module.exports = {
// NOTE: the caller will concatenate the bytecode and this
// it could be done here too for consistency
var abiCoder = new ethers.utils.AbiCoder()
const abiCoder = new ethers.utils.AbiCoder()
return abiCoder.encode(types, args)
},
encodeFunctionId: function (funABI) {
if (funABI.type === 'fallback') return '0x'
var abi = new ethers.utils.Interface([funABI])
let abi = new ethers.utils.Interface([funABI])
abi = abi.functions[funABI.name]
return abi.sighash
},
@ -63,7 +63,7 @@ module.exports = {
},
getConstructorInterface: function (abi) {
var funABI = { 'name': '', 'inputs': [], 'type': 'constructor', 'payable': 'false', 'outputs': [] }
const funABI = { 'name': '', 'inputs': [], 'type': 'constructor', 'payable': 'false', 'outputs': [] }
if (typeof abi === 'string') {
try {
abi = JSON.parse(abi)
@ -73,7 +73,7 @@ module.exports = {
}
}
for (var i = 0; i < abi.length; i++) {
for (let i = 0; i < abi.length; i++) {
if (abi[i].type === 'constructor') {
funABI.inputs = abi[i].inputs || []
funABI.payable = abi[i].payable
@ -86,7 +86,7 @@ module.exports = {
},
serializeInputs: function (fnAbi) {
var serialized = '('
let serialized = '('
if (fnAbi.inputs && fnAbi.inputs.length) {
serialized += fnAbi.inputs.map((input) => { return input.type }).join(',')
}
@ -95,13 +95,13 @@ module.exports = {
},
extractSize: function (type) {
var size = type.match(/([a-zA-Z0-9])(\[.*\])/)
const size = type.match(/([a-zA-Z0-9])(\[.*\])/)
return size ? size[2] : ''
},
getFunction: function (abi, fnName) {
for (var i = 0; i < abi.length; i++) {
var fn = abi[i]
for (let i = 0; i < abi.length; i++) {
const fn = abi[i]
if (fn.type === 'function' && fnName === fn.name + '(' + fn.inputs.map((value) => {
if (value.components) {
let fullType = this.makeFullTypeDefinition(value)
@ -117,7 +117,7 @@ module.exports = {
},
getFallbackInterface: function (abi) {
for (var i = 0; i < abi.length; i++) {
for (let i = 0; i < abi.length; i++) {
if (abi[i].type === 'fallback') {
return abi[i]
}
@ -131,7 +131,7 @@ module.exports = {
* @returns contract obj and associated file: { contract, file } or null
*/
getContract: (contractName, contracts) => {
for (var file in contracts) {
for (let file in contracts) {
if (contracts[file][contractName]) {
return { object: contracts[file][contractName], file: file }
}
@ -145,17 +145,16 @@ module.exports = {
* @param {Function} cb - callback
*/
visitContracts: (contracts, cb) => {
for (var file in contracts) {
for (var name in contracts[file]) {
for (let file in contracts) {
for (let name in contracts[file]) {
if (cb({ name: name, object: contracts[file][name], file: file })) return
}
}
},
inputParametersDeclarationToString: function (abiinputs) {
var inputs = (abiinputs || []).map((inp) => inp.type + ' ' + inp.name)
const inputs = (abiinputs || []).map((inp) => inp.type + ' ' + inp.name)
return inputs.join(', ')
}
}

@ -1,13 +1,13 @@
'use strict'
var async = require('async')
var ethers = require('ethers')
var ethJSUtil = require('ethereumjs-util')
var EventManager = require('../eventManager')
var codeUtil = require('../util')
const async = require('async')
const ethers = require('ethers')
const ethJSUtil = require('ethereumjs-util')
const EventManager = require('../eventManager')
const codeUtil = require('../util')
var defaultExecutionContext = require('./execution-context')
var txFormat = require('./txFormat')
var txHelper = require('./txHelper')
const defaultExecutionContext = require('./execution-context')
const txFormat = require('./txFormat')
const txHelper = require('./txHelper')
/**
* poll web3 each 2s if web3
@ -17,6 +17,7 @@ var txHelper = require('./txHelper')
*
*/
class TxListener {
constructor (opt, executionContext) {
this.event = new EventManager()
// has a default for now for backwards compatability
@ -43,7 +44,7 @@ class TxListener {
if (!this._isListening) return // we don't listen
if (this._loopId && this.executionContext.getProvider() !== 'vm') return // we seems to already listen on a "web3" network
var call = {
const call = {
from: from,
to: to,
input: data,
@ -144,13 +145,13 @@ class TxListener {
_startListenOnNetwork () {
this._loopId = setInterval(() => {
var currentLoopId = this._loopId
const currentLoopId = this._loopId
this.executionContext.web3().eth.getBlockNumber((error, blockNumber) => {
if (this._loopId === null) return
if (error) return console.log(error)
if (currentLoopId === this._loopId && (!this.lastBlock || blockNumber > this.lastBlock)) {
if (!this.lastBlock) this.lastBlock = blockNumber - 1
var current = this.lastBlock + 1
let current = this.lastBlock + 1
this.lastBlock = blockNumber
while (blockNumber >= current) {
try {
@ -219,18 +220,18 @@ class TxListener {
}
_resolveTx (tx, receipt, cb) {
var contracts = this._api.contracts()
const contracts = this._api.contracts()
if (!contracts) return cb()
var contractName
var fun
let contractName
let fun
if (!tx.to || tx.to === '0x0') { // testrpc returns 0x0 in that case
// contract creation / resolve using the creation bytes code
// if web3: we have to call getTransactionReceipt to get the created address
// if VM: created address already included
var code = tx.input
const code = tx.input
contractName = this._tryResolveContract(code, contracts, true)
if (contractName) {
var address = receipt.contractAddress
let address = receipt.contractAddress
this._resolvedContracts[address] = contractName
fun = this._resolveFunction(contractName, contracts, tx, true)
if (this._resolvedTransactions[tx.hash]) {
@ -246,10 +247,10 @@ class TxListener {
this.executionContext.web3().eth.getCode(tx.to, (error, code) => {
if (error) return cb(error)
if (code) {
var contractName = this._tryResolveContract(code, contracts, false)
const contractName = this._tryResolveContract(code, contracts, false)
if (contractName) {
this._resolvedContracts[tx.to] = contractName
var fun = this._resolveFunction(contractName, contracts, tx, false)
const fun = this._resolveFunction(contractName, contracts, tx, false)
return cb(null, {to: tx.to, contractName: contractName, function: fun})
}
}
@ -266,18 +267,18 @@ class TxListener {
}
_resolveFunction (contractName, compiledContracts, tx, isCtor) {
var contract = txHelper.getContract(contractName, compiledContracts)
const contract = txHelper.getContract(contractName, compiledContracts)
if (!contract) {
console.log('txListener: cannot resolve ' + contractName)
return
}
var abi = contract.object.abi
var inputData = tx.input.replace('0x', '')
const abi = contract.object.abi
const inputData = tx.input.replace('0x', '')
if (!isCtor) {
var methodIdentifiers = contract.object.evm.methodIdentifiers
for (var fn in methodIdentifiers) {
const methodIdentifiers = contract.object.evm.methodIdentifiers
for (let fn in methodIdentifiers) {
if (methodIdentifiers[fn] === inputData.substring(0, 8)) {
var fnabi = txHelper.getFunction(abi, fn)
const fnabi = txHelper.getFunction(abi, fn)
this._resolvedTransactions[tx.hash] = {
contractName: contractName,
to: tx.to,
@ -298,8 +299,8 @@ class TxListener {
params: null
}
} else {
var bytecode = contract.object.evm.bytecode.object
var params = null
const bytecode = contract.object.evm.bytecode.object
let params = null
if (bytecode && bytecode.length) {
params = this._decodeInputParams(inputData.substring(bytecode.length), txHelper.getConstructorInterface(abi))
}
@ -314,9 +315,9 @@ class TxListener {
}
_tryResolveContract (codeToResolve, compiledContracts, isCreation) {
var found = null
let found = null
txHelper.visitContracts(compiledContracts, (contract) => {
var bytes = isCreation ? contract.object.evm.bytecode.object : contract.object.evm.deployedBytecode.object
const bytes = isCreation ? contract.object.evm.bytecode.object : contract.object.evm.deployedBytecode.object
if (codeUtil.compareByteCode(codeToResolve, '0x' + bytes)) {
found = contract.name
return true
@ -329,14 +330,14 @@ class TxListener {
data = ethJSUtil.toBuffer('0x' + data)
if (!data.length) data = new Uint8Array(32 * abi.inputs.length) // ensuring the data is at least filled by 0 cause `AbiCoder` throws if there's not engouh data
var inputTypes = []
for (var i = 0; i < abi.inputs.length; i++) {
var type = abi.inputs[i].type
const inputTypes = []
for (let i = 0; i < abi.inputs.length; i++) {
const type = abi.inputs[i].type
inputTypes.push(type.indexOf('tuple') === 0 ? txHelper.makeFullTypeDefinition(abi.inputs[i]) : type)
}
var abiCoder = new ethers.utils.AbiCoder()
var decoded = abiCoder.decode(inputTypes, data)
var ret = {}
const abiCoder = new ethers.utils.AbiCoder()
const decoded = abiCoder.decode(inputTypes, data)
const ret = {}
for (var k in abi.inputs) {
ret[abi.inputs[k].type + ' ' + abi.inputs[k].name] = decoded[k]
}

@ -1,10 +1,10 @@
'use strict'
var EthJSTX = require('ethereumjs-tx').Transaction
var EthJSBlock = require('ethereumjs-block')
var ethJSUtil = require('ethereumjs-util')
var BN = ethJSUtil.BN
var defaultExecutionContext = require('./execution-context')
var EventManager = require('../eventManager')
const EthJSTX = require('ethereumjs-tx').Transaction
const EthJSBlock = require('ethereumjs-block')
const ethJSUtil = require('ethereumjs-util')
const BN = ethJSUtil.BN
const defaultExecutionContext = require('./execution-context')
const EventManager = require('../eventManager')
class TxRunner {
constructor (vmaccounts, api, executionContext) {
@ -26,7 +26,7 @@ class TxRunner {
}
rawRun (args, confirmationCb, gasEstimationForceSend, promptCb, cb) {
var timestamp = Date.now()
let timestamp = Date.now()
if (args.timestamp) {
timestamp = args.timestamp
}
@ -50,15 +50,14 @@ class TxRunner {
}
_sendTransaction (sendTx, tx, pass, callback) {
var self = this
var cb = function (err, resp) {
const cb = (err, resp) => {
if (err) {
return callback(err, resp)
}
self.event.trigger('transactionBroadcasted', [resp])
this.event.trigger('transactionBroadcasted', [resp])
var listenOnResponse = () => {
return new Promise(async (resolve, reject) => {
var result = await tryTillReceiptAvailable(resp)
const result = await tryTillReceiptAvailable(resp)
tx = await tryTillTxAvailable(resp)
resolve({
result,
@ -69,7 +68,7 @@ class TxRunner {
}
listenOnResponse().then((txData) => { callback(null, txData) }).catch((error) => { callback(error) })
}
var args = pass !== null ? [tx, pass, cb] : [tx, cb]
const args = pass !== null ? [tx, pass, cb] : [tx, cb]
try {
sendTx.apply({}, args)
} catch (e) {
@ -78,18 +77,16 @@ class TxRunner {
}
execute (args, confirmationCb, gasEstimationForceSend, promptCb, callback) {
var self = this
var data = args.data
let data = args.data
if (data.slice(0, 2) !== '0x') {
data = '0x' + data
}
if (!this.executionContext.isVM()) {
self.runInNode(args.from, args.to, data, args.value, args.gasLimit, args.useCall, confirmationCb, gasEstimationForceSend, promptCb, callback)
this.runInNode(args.from, args.to, data, args.value, args.gasLimit, args.useCall, confirmationCb, gasEstimationForceSend, promptCb, callback)
} else {
try {
self.runInVm(args.from, args.to, data, args.value, args.gasLimit, args.useCall, args.timestamp, callback)
this.runInVm(args.from, args.to, data, args.value, args.gasLimit, args.useCall, args.timestamp, callback)
} catch (e) {
callback(e, null)
}
@ -165,8 +162,7 @@ class TxRunner {
}
runInNode (from, to, data, value, gasLimit, useCall, confirmCb, gasEstimationForceSend, promptCb, callback) {
const self = this
var tx = { from: from, to: to, data: data, value: value }
const tx = { from: from, to: to, data: data, value: value }
if (useCall) {
tx.gas = gasLimit
@ -177,34 +173,34 @@ class TxRunner {
})
})
}
this.executionContext.web3().eth.estimateGas(tx, function (err, gasEstimation) {
this.executionContext.web3().eth.estimateGas(tx, (err, gasEstimation) => {
gasEstimationForceSend(err, () => {
// callback is called whenever no error
tx.gas = !gasEstimation ? gasLimit : gasEstimation
if (self._api.config.getUnpersistedProperty('doNotShowTransactionConfirmationAgain')) {
return self._executeTx(tx, null, self._api, promptCb, callback)
if (this._api.config.getUnpersistedProperty('doNotShowTransactionConfirmationAgain')) {
return this._executeTx(tx, null, this._api, promptCb, callback)
}
self._api.detectNetwork((err, network) => {
this._api.detectNetwork((err, network) => {
if (err) {
console.log(err)
return
}
confirmCb(network, tx, tx.gas, (gasPrice) => {
return self._executeTx(tx, gasPrice, self._api, promptCb, callback)
return this._executeTx(tx, gasPrice, this._api, promptCb, callback)
}, (error) => {
callback(error)
})
})
}, () => {
var blockGasLimit = self.executionContext.currentblockGasLimit()
const blockGasLimit = this.executionContext.currentblockGasLimit()
// NOTE: estimateGas very likely will return a large limit if execution of the code failed
// we want to be able to run the code in order to debug and find the cause for the failure
if (err) return callback(err)
var warnEstimation = ' An important gas estimation might also be the sign of a problem in the contract code. Please check loops and be sure you did not sent value to a non payable function (that\'s also the reason of strong gas estimation). '
let warnEstimation = ' An important gas estimation might also be the sign of a problem in the contract code. Please check loops and be sure you did not sent value to a non payable function (that\'s also the reason of strong gas estimation). '
warnEstimation += ' ' + err
if (gasEstimation > gasLimit) {
@ -257,7 +253,7 @@ function run (self, tx, stamp, confirmationCb, gasEstimationForceSend, promptCb,
delete self.pendingTxs[stamp]
callback(error, result)
if (self.queusTxs.length) {
var next = self.queusTxs.pop()
const next = self.queusTxs.pop()
run(self, next.tx, next.stamp, next.callback)
}
})

@ -1,6 +1,6 @@
'use strict'
var ethJSUtil = require('ethereumjs-util')
var BN = ethJSUtil.BN
const ethJSUtil = require('ethereumjs-util')
const BN = ethJSUtil.BN
module.exports = {
toInt: (h) => {
@ -17,7 +17,7 @@ module.exports = {
function stringify (v) {
try {
if (v instanceof Array) {
var ret = []
const ret = []
for (var k in v) {
ret.push(stringify(v[k]))
}
@ -27,8 +27,8 @@ function stringify (v) {
} else if (v._isBuffer) {
return ethJSUtil.bufferToHex(v)
} else if (typeof v === 'object') {
var retObject = {}
for (var i in v) {
const retObject = {}
for (let i in v) {
retObject[i] = stringify(v[i])
}
return retObject

@ -1,13 +1,14 @@
'use strict'
var ui = require('./uiHelper')
const ui = require('./uiHelper')
module.exports = {
// vmTraceIndex has to point to a CALL, CODECALL, ...
resolveCalledAddress: function (vmTraceIndex, trace) {
var step = trace[vmTraceIndex]
const step = trace[vmTraceIndex]
if (this.isCreateInstruction(step)) {
return this.contractCreationToken(vmTraceIndex)
} else if (this.isCallInstruction(step)) {
var stack = step.stack // callcode, delegatecall, ...
const stack = step.stack // callcode, delegatecall, ...
return ui.normalizeHexAddress(stack[stack.length - 2])
}
return undefined
@ -51,7 +52,7 @@ module.exports = {
isCallToPrecompiledContract: function (index, trace) {
// if stack empty => this is not a precompiled contract
var step = trace[index]
const step = trace[index]
if (this.isCallInstruction(step)) {
return index + 1 < trace.length && trace[index + 1].stack.length !== 0
} else {

@ -1,7 +1,7 @@
'use strict'
module.exports = {
formatMemory: function (mem, width) {
var ret = {}
const ret = {}
if (!mem) {
return ret
}
@ -10,19 +10,19 @@ module.exports = {
mem = mem.join('') // geth returns an array, eth return raw string
}
for (var k = 0; k < mem.length; k += (width * 2)) {
var memory = mem.substr(k, width * 2)
var content = this.tryConvertAsciiFormat(memory)
for (let k = 0; k < mem.length; k += (width * 2)) {
const memory = mem.substr(k, width * 2)
const content = this.tryConvertAsciiFormat(memory)
ret['0x' + (k / 2).toString(16)] = content.raw + '\t' + content.ascii
}
return ret
},
tryConvertAsciiFormat: function (memorySlot) {
var ret = { ascii: '', raw: '' }
for (var k = 0; k < memorySlot.length; k += 2) {
var raw = memorySlot.substr(k, 2)
var ascii = String.fromCharCode(parseInt(raw, 16))
const ret = { ascii: '', raw: '' }
for (let k = 0; k < memorySlot.length; k += 2) {
const raw = memorySlot.substr(k, 2)
let ascii = String.fromCharCode(parseInt(raw, 16))
ascii = ascii.replace(/[^\w\s]/, '?')
if (ascii === '') {
ascii = '?'
@ -45,9 +45,9 @@ module.exports = {
* used if multiple occurences of the same key is needed
*/
formatCss: function (css1, css2) {
var ret = ''
for (var arg in arguments) {
for (var k in arguments[arg]) {
let ret = ''
for (let arg in arguments) {
for (let k in arguments[arg]) {
if (arguments[arg][k] && ret.indexOf(k) === -1) {
if (k.indexOf('*') === 0) {
ret += arguments[arg][k]
@ -71,7 +71,7 @@ module.exports = {
normalizeHexAddress: function (hex) {
if (hex.indexOf('0x') === 0) hex = hex.replace('0x', '')
if (hex.length >= 40) {
var reg = /(.{40})$/.exec(hex)
const reg = /(.{40})$/.exec(hex)
if (reg) {
return '0x' + reg[0]
}

@ -1,10 +1,10 @@
'use strict'
var Web3 = require('web3')
const Web3 = require('web3')
module.exports = {
loadWeb3: function (url) {
if (!url) url = 'http://localhost:8545'
var web3 = new Web3()
const web3 = new Web3()
web3.setProvider(new web3.providers.HttpProvider(url))
this.extend(web3)
return web3
@ -30,7 +30,7 @@ module.exports = {
return
}
// DEBUG
var methods = []
const methods = []
if (!(web3.debug && web3.debug.preimage)) {
methods.push(new web3.extend.Method({
name: 'preimage',
@ -67,7 +67,7 @@ module.exports = {
}
}
var web3DebugNodes = {
const web3DebugNodes = {
'Main': 'https://mainnet.infura.io/remix',
'Rinkeby': 'https://remix-rinkeby.ethdevops.io',
'Ropsten': 'https://remix-ropsten.ethdevops.io',

@ -1,12 +1,12 @@
'use strict'
var SourceMappingDecoder = require('./sourceMappingDecoder')
const SourceMappingDecoder = require('./sourceMappingDecoder')
function offsetToColumnConverter (compilerEvent) {
this.lineBreakPositionsByContent = {}
this.sourceMappingDecoder = new SourceMappingDecoder()
var self = this
if (compilerEvent) {
compilerEvent.register('compilationFinished', function (success, data, source) {
compilerEvent.register('compilationFinished', (success, data, source) => {
self.clear()
})
}
@ -14,8 +14,8 @@ function offsetToColumnConverter (compilerEvent) {
offsetToColumnConverter.prototype.offsetToLineColumn = function (rawLocation, file, sources, asts) {
if (!this.lineBreakPositionsByContent[file]) {
for (var filename in asts) {
var source = asts[filename]
for (let filename in asts) {
const source = asts[filename]
// source id was string before. in newer versions it has been changed to an integer so we need to check the type here
if (typeof source.id === 'string') source.id = parseInt(source.id, 10)
if (source.id === file) {

@ -1,8 +1,8 @@
'use strict'
var EventManager = require('./eventManager')
var helper = require('./helpers/traceHelper')
var SourceMappingDecoder = require('./sourceMappingDecoder')
var util = require('./util')
const EventManager = require('./eventManager')
const helper = require('./helpers/traceHelper')
const SourceMappingDecoder = require('./sourceMappingDecoder')
const util = require('./util')
/**
* Process the source code location for the current executing bytecode
@ -23,12 +23,11 @@ function SourceLocationTracker (_codeManager) {
* @param {Function} cb - callback function
*/
SourceLocationTracker.prototype.getSourceLocationFromInstructionIndex = function (address, index, contracts, cb) {
var self = this
extractSourceMap(this, this.codeManager, address, contracts, function (error, sourceMap) {
extractSourceMap(this, this.codeManager, address, contracts, (error, sourceMap) => {
if (error) {
cb(error)
} else {
cb(null, self.sourceMappingDecoder.atIndex(index, sourceMap))
cb(null, this.sourceMappingDecoder.atIndex(index, sourceMap))
}
})
}
@ -42,14 +41,13 @@ SourceLocationTracker.prototype.getSourceLocationFromInstructionIndex = function
* @param {Function} cb - callback function
*/
SourceLocationTracker.prototype.getSourceLocationFromVMTraceIndex = function (address, vmtraceStepIndex, contracts, cb) {
var self = this
extractSourceMap(this, this.codeManager, address, contracts, function (error, sourceMap) {
extractSourceMap(this, this.codeManager, address, contracts, (error, sourceMap) => {
if (!error) {
self.codeManager.getInstructionIndex(address, vmtraceStepIndex, function (error, index) {
this.codeManager.getInstructionIndex(address, vmtraceStepIndex, (error, index) => {
if (error) {
cb(error)
} else {
cb(null, self.sourceMappingDecoder.atIndex(index, sourceMap))
cb(null, this.sourceMappingDecoder.atIndex(index, sourceMap))
}
})
} else {
@ -63,10 +61,10 @@ SourceLocationTracker.prototype.clearCache = function () {
}
function getSourceMap (address, code, contracts) {
var isCreation = helper.isContractCreation(address)
var bytes
for (var file in contracts) {
for (var contract in contracts[file]) {
const isCreation = helper.isContractCreation(address)
let bytes
for (let file in contracts) {
for (let contract in contracts[file]) {
bytes = isCreation ? contracts[file][contract].evm.bytecode.object : contracts[file][contract].evm.deployedBytecode.object
if (util.compareByteCode(code, '0x' + bytes)) {
return isCreation ? contracts[file][contract].evm.bytecode.sourceMap : contracts[file][contract].evm.deployedBytecode.sourceMap
@ -79,9 +77,9 @@ function getSourceMap (address, code, contracts) {
function extractSourceMap (self, codeManager, address, contracts, cb) {
if (self.sourceMapByAddress[address]) return cb(null, self.sourceMapByAddress[address])
codeManager.getCode(address, function (error, result) {
codeManager.getCode(address, (error, result) => {
if (!error) {
var sourceMap = getSourceMap(address, result.bytecode, contracts)
const sourceMap = getSourceMap(address, result.bytecode, contracts)
if (sourceMap) {
if (!helper.isContractCreation(address)) self.sourceMapByAddress[address] = sourceMap
cb(null, sourceMap)

@ -1,6 +1,6 @@
'use strict'
var util = require('./util')
var AstWalker = require('./astWalker')
const util = require('./util')
const AstWalker = require('./astWalker')
/**
* Decompress the source mapping given by solc-bin.js
@ -51,11 +51,11 @@ SourceMappingDecoder.prototype.decode = function (value) {
* @return {Array} returns the decompressed source mapping. Array of {start, length, file, jump}
*/
SourceMappingDecoder.prototype.decompressAll = function (mapping) {
var map = mapping.split(';')
var ret = []
for (var k in map) {
var compressed = map[k].split(':')
var sourceMap = {
const map = mapping.split(';')
const ret = []
for (let k in map) {
const compressed = map[k].split(':')
const sourceMap = {
start: compressed[0] ? parseInt(compressed[0]) : ret[ret.length - 1].start,
length: compressed[1] ? parseInt(compressed[1]) : ret[ret.length - 1].length,
file: compressed[2] ? parseInt(compressed[2]) : ret[ret.length - 1].file,
@ -73,8 +73,8 @@ SourceMappingDecoder.prototype.decompressAll = function (mapping) {
* @return {Array} returns an array containing offset of line breaks
*/
SourceMappingDecoder.prototype.getLinebreakPositions = function (source) {
var ret = []
for (var pos = source.indexOf('\n'); pos >= 0; pos = source.indexOf('\n', pos + 1)) {
const ret = []
for (let pos = source.indexOf('\n'); pos >= 0; pos = source.indexOf('\n', pos + 1)) {
ret.push(pos)
}
return ret
@ -112,12 +112,12 @@ SourceMappingDecoder.prototype.convertOffsetToLineColumn = function (sourceLocat
SourceMappingDecoder.prototype.findNodeAtInstructionIndex = findNodeAtInstructionIndex
function convertFromCharPosition (pos, lineBreakPositions) {
var line = util.findLowerBound(pos, lineBreakPositions)
let line = util.findLowerBound(pos, lineBreakPositions)
if (lineBreakPositions[line] !== pos) {
line = line + 1
}
var beginColumn = line === 0 ? 0 : (lineBreakPositions[line - 1] + 1)
var column = pos - beginColumn
const beginColumn = line === 0 ? 0 : (lineBreakPositions[line - 1] + 1)
const column = pos - beginColumn
return {
line: line,
column: column
@ -126,7 +126,7 @@ function convertFromCharPosition (pos, lineBreakPositions) {
function sourceLocationFromAstNode (astNode) {
if (astNode.src) {
var split = astNode.src.split(':')
const split = astNode.src.split(':')
return {
start: parseInt(split[0]),
length: parseInt(split[1]),
@ -137,16 +137,16 @@ function sourceLocationFromAstNode (astNode) {
}
function findNodeAtInstructionIndex (astNodeType, instIndex, sourceMap, ast) {
var sourceLocation = atIndex(instIndex, sourceMap)
const sourceLocation = atIndex(instIndex, sourceMap)
return findNodeAtSourceLocation(astNodeType, sourceLocation, ast)
}
function findNodeAtSourceLocation (astNodeType, sourceLocation, ast) {
var astWalker = new AstWalker()
var callback = {}
var found = null
const astWalker = new AstWalker()
const callback = {}
let found = null
callback['*'] = function (node) {
var nodeLocation = sourceLocationFromAstNode(node)
const nodeLocation = sourceLocationFromAstNode(node)
if (!nodeLocation) {
return true
}
@ -166,9 +166,9 @@ function findNodeAtSourceLocation (astNodeType, sourceLocation, ast) {
}
function nodesAtPosition (astNodeType, position, ast) {
var astWalker = new AstWalker()
var callback = {}
var found = []
const astWalker = new AstWalker()
const callback = {}
const found = []
callback['*'] = function (node) {
var nodeLocation = sourceLocationFromAstNode(node)
if (!nodeLocation) {
@ -189,13 +189,13 @@ function nodesAtPosition (astNodeType, position, ast) {
}
function atIndex (index, mapping) {
var ret = {}
var map = mapping.split(';')
const ret = {}
const map = mapping.split(';')
if (index >= map.length) {
index = map.length - 1
}
for (var k = index; k >= 0; k--) {
var current = map[k]
for (let k = index; k >= 0; k--) {
let current = map[k]
if (!current.length) {
continue
}

@ -34,7 +34,7 @@ function Storage (prefix) {
}
this.rename = function (originalName, newName) {
var content = this.get(originalName)
const content = this.get(originalName)
if (!this.set(newName, content)) {
return false
}

@ -1,5 +1,5 @@
'use strict'
var traceHelper = require('../helpers/traceHelper')
const traceHelper = require('../helpers/traceHelper')
function TraceAnalyser (_cache) {
this.traceCache = _cache
@ -9,19 +9,19 @@ function TraceAnalyser (_cache) {
TraceAnalyser.prototype.analyse = function (trace, tx, callback) {
this.trace = trace
this.traceCache.pushStoreChanges(0, tx.to)
var context = {
let context = {
storageContext: [tx.to],
currentCallIndex: 0,
lastCallIndex: 0
}
var callStack = [tx.to]
const callStack = [tx.to]
this.traceCache.pushCall(trace[0], 0, callStack[0], callStack.slice(0))
if (traceHelper.isContractCreation(tx.to)) {
this.traceCache.pushContractCreation(tx.to, tx.input)
}
this.buildCalldata(0, this.trace[0], tx, true)
for (var k = 0; k < this.trace.length; k++) {
var step = this.trace[k]
for (let k = 0; k < this.trace.length; k++) {
const step = this.trace[k]
this.buildMemory(k, step)
context = this.buildDepth(k, step, tx, callStack, context)
context = this.buildStorage(k, step, context)
@ -32,27 +32,27 @@ TraceAnalyser.prototype.analyse = function (trace, tx, callback) {
TraceAnalyser.prototype.buildReturnValues = function (index, step) {
if (traceHelper.isReturnInstruction(step)) {
var offset = 2 * parseInt(step.stack[step.stack.length - 1], 16)
var size = 2 * parseInt(step.stack[step.stack.length - 2], 16)
var memory = this.trace[this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]].memory
const offset = 2 * parseInt(step.stack[step.stack.length - 1], 16)
const size = 2 * parseInt(step.stack[step.stack.length - 2], 16)
const memory = this.trace[this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]].memory
this.traceCache.pushReturnValue(index, '0x' + memory.join('').substr(offset, size))
}
}
TraceAnalyser.prototype.buildCalldata = function (index, step, tx, newContext) {
var calldata = ''
let calldata = ''
if (index === 0) {
calldata = tx.input
this.traceCache.pushCallDataChanges(index, calldata)
} else if (!newContext) {
var lastCall = this.traceCache.callsData[this.traceCache.callDataChanges[this.traceCache.callDataChanges.length - 2]]
const lastCall = this.traceCache.callsData[this.traceCache.callDataChanges[this.traceCache.callDataChanges.length - 2]]
this.traceCache.pushCallDataChanges(index + 1, lastCall)
} else {
var memory = this.trace[this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]].memory
var callStep = this.trace[index]
var stack = callStep.stack
var offset = ''
var size = ''
const memory = this.trace[this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]].memory
const callStep = this.trace[index]
const stack = callStep.stack
let offset = ''
let size = ''
if (callStep.op === 'DELEGATECALL') {
offset = 2 * parseInt(stack[stack.length - 3], 16)
size = 2 * parseInt(stack[stack.length - 4], 16)
@ -73,7 +73,7 @@ TraceAnalyser.prototype.buildMemory = function (index, step) {
TraceAnalyser.prototype.buildStorage = function (index, step, context) {
if (traceHelper.newContextStorage(step) && !traceHelper.isCallToPrecompiledContract(index, this.trace)) {
var calledAddress = traceHelper.resolveCalledAddress(index, this.trace)
const calledAddress = traceHelper.resolveCalledAddress(index, this.trace)
if (calledAddress) {
context.storageContext.push(calledAddress)
} else {
@ -94,11 +94,11 @@ TraceAnalyser.prototype.buildStorage = function (index, step, context) {
TraceAnalyser.prototype.buildDepth = function (index, step, tx, callStack, context) {
if (traceHelper.isCallInstruction(step) && !traceHelper.isCallToPrecompiledContract(index, this.trace)) {
var newAddress
let newAddress
if (traceHelper.isCreateInstruction(step)) {
newAddress = traceHelper.contractCreationToken(index)
callStack.push(newAddress)
var lastMemoryChange = this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]
const lastMemoryChange = this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]
this.traceCache.pushContractCreationFromMemory(index, newAddress, this.trace, lastMemoryChange)
} else {
newAddress = traceHelper.resolveCalledAddress(index, this.trace)

@ -1,5 +1,5 @@
'use strict'
var helper = require('../util')
const helper = require('../util')
function TraceCache () {
this.init()
@ -38,7 +38,7 @@ TraceCache.prototype.pushMemoryChanges = function (value) {
// outOfGas has been removed because gas left logging is apparently made differently
// in the vm/geth/eth. TODO add the error property (with about the error in all clients)
TraceCache.prototype.pushCall = function (step, index, address, callStack, reverted) {
var validReturnStep = step.op === 'RETURN' || step.op === 'STOP'
let validReturnStep = step.op === 'RETURN' || step.op === 'STOP'
if (validReturnStep || reverted) {
if (this.currentCall) {
this.currentCall.call.return = index - 1
@ -49,7 +49,7 @@ TraceCache.prototype.pushCall = function (step, index, address, callStack, rever
this.currentCall = parent ? { call: parent.call, parent: parent.parent } : null
}
} else {
var call = {
let call = {
op: step.op,
address: address,
callStack: callStack,
@ -71,10 +71,10 @@ TraceCache.prototype.pushReturnValue = function (step, value) {
}
TraceCache.prototype.pushContractCreationFromMemory = function (index, token, trace, lastMemoryChange) {
var memory = trace[lastMemoryChange].memory
var stack = trace[index].stack
var offset = 2 * parseInt(stack[stack.length - 2], 16)
var size = 2 * parseInt(stack[stack.length - 3], 16)
const memory = trace[lastMemoryChange].memory
const stack = trace[index].stack
const offset = 2 * parseInt(stack[stack.length - 2], 16)
const size = 2 * parseInt(stack[stack.length - 3], 16)
this.contractCreation[token] = '0x' + memory.join('').substr(offset, size)
}
@ -98,9 +98,9 @@ TraceCache.prototype.pushStoreChanges = function (index, address, key, value) {
}
TraceCache.prototype.accumulateStorageChanges = function (index, address, storage) {
var ret = Object.assign({}, storage)
const ret = Object.assign({}, storage)
for (var k in this.storageChanges) {
var changesIndex = this.storageChanges[k]
const changesIndex = this.storageChanges[k]
if (changesIndex > index) {
return ret
}

@ -1,11 +1,11 @@
'use strict'
var TraceAnalyser = require('./traceAnalyser')
var TraceRetriever = require('./traceRetriever')
var TraceCache = require('./traceCache')
var TraceStepManager = require('./traceStepManager')
const TraceAnalyser = require('./traceAnalyser')
const TraceRetriever = require('./traceRetriever')
const TraceCache = require('./traceCache')
const TraceStepManager = require('./traceStepManager')
var traceHelper = require('../helpers/traceHelper')
var util = require('../util')
const traceHelper = require('../helpers/traceHelper')
const util = require('../util')
function TraceManager (options) {
this.web3 = options.web3
@ -25,7 +25,7 @@ TraceManager.prototype.resolveTrace = function (tx, callback) {
if (!this.web3) callback('web3 not loaded', false)
this.isLoading = true
var self = this
this.traceRetriever.getTrace(tx.hash, function (error, result) {
this.traceRetriever.getTrace(tx.hash, (error, result) => {
if (error) {
console.log(error)
self.isLoading = false
@ -76,7 +76,7 @@ TraceManager.prototype.getLength = function (callback) {
}
TraceManager.prototype.accumulateStorageChanges = function (index, address, storageOrigin, callback) {
var storage = this.traceCache.accumulateStorageChanges(index, address, storageOrigin)
const storage = this.traceCache.accumulateStorageChanges(index, address, storageOrigin)
callback(null, storage)
}
@ -85,41 +85,41 @@ TraceManager.prototype.getAddresses = function (callback) {
}
TraceManager.prototype.getCallDataAt = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
var callDataChange = util.findLowerBoundValue(stepIndex, this.traceCache.callDataChanges)
const callDataChange = util.findLowerBoundValue(stepIndex, this.traceCache.callDataChanges)
if (callDataChange === null) return callback('no calldata found', null)
callback(null, [this.traceCache.callsData[callDataChange]])
}
TraceManager.prototype.buildCallPath = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
var callsPath = util.buildCallPath(stepIndex, this.traceCache.callsTree.call)
const callsPath = util.buildCallPath(stepIndex, this.traceCache.callsTree.call)
if (callsPath === null) return callback('no call path built', null)
callback(null, callsPath)
}
TraceManager.prototype.getCallStackAt = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
var call = util.findCall(stepIndex, this.traceCache.callsTree.call)
const call = util.findCall(stepIndex, this.traceCache.callsTree.call)
if (call === null) return callback('no callstack found', null)
callback(null, call.callStack)
}
TraceManager.prototype.getStackAt = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
var stack
let stack
if (this.trace[stepIndex] && this.trace[stepIndex].stack) { // there's always a stack
stack = this.trace[stepIndex].stack.slice(0)
stack.reverse()
@ -130,11 +130,11 @@ TraceManager.prototype.getStackAt = function (stepIndex, callback) {
}
TraceManager.prototype.getLastCallChangeSince = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
var callChange = util.findCall(stepIndex, this.traceCache.callsTree.call)
const callChange = util.findCall(stepIndex, this.traceCache.callsTree.call)
if (callChange === null) {
callback(null, 0)
} else {
@ -143,7 +143,7 @@ TraceManager.prototype.getLastCallChangeSince = function (stepIndex, callback) {
}
TraceManager.prototype.getCurrentCalledAddressAt = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
@ -169,17 +169,17 @@ TraceManager.prototype.getContractCreationCode = function (token, callback) {
}
TraceManager.prototype.getMemoryAt = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
var lastChanges = util.findLowerBoundValue(stepIndex, this.traceCache.memoryChanges)
const lastChanges = util.findLowerBoundValue(stepIndex, this.traceCache.memoryChanges)
if (lastChanges === null) return callback('no memory found', null)
callback(null, this.trace[lastChanges].memory)
}
TraceManager.prototype.getCurrentPC = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
@ -187,7 +187,7 @@ TraceManager.prototype.getCurrentPC = function (stepIndex, callback) {
}
TraceManager.prototype.getReturnValue = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
@ -199,7 +199,7 @@ TraceManager.prototype.getReturnValue = function (stepIndex, callback) {
}
TraceManager.prototype.getCurrentStep = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
@ -207,7 +207,7 @@ TraceManager.prototype.getCurrentStep = function (stepIndex, callback) {
}
TraceManager.prototype.getMemExpand = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
@ -215,7 +215,7 @@ TraceManager.prototype.getMemExpand = function (stepIndex, callback) {
}
TraceManager.prototype.getStepCost = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
@ -223,7 +223,7 @@ TraceManager.prototype.getStepCost = function (stepIndex, callback) {
}
TraceManager.prototype.getRemainingGas = function (stepIndex, callback) {
var check = this.checkRequestedStep(stepIndex)
const check = this.checkRequestedStep(stepIndex)
if (check) {
return callback(check, null)
}
@ -262,8 +262,8 @@ TraceManager.prototype.checkRequestedStep = function (stepIndex) {
}
TraceManager.prototype.waterfall = function (calls, stepindex, cb) {
var ret = []
var retError = null
let ret = []
let retError = null
for (var call in calls) {
calls[call].apply(this, [stepindex, function (error, result) {
retError = error

@ -5,7 +5,7 @@ function TraceRetriever (options) {
}
TraceRetriever.prototype.getTrace = function (txHash, callback) {
var options = {
const options = {
disableStorage: true,
disableMemory: false,
disableStack: false,

@ -1,25 +1,25 @@
'use strict'
var traceHelper = require('../helpers/traceHelper')
var util = require('../util')
const traceHelper = require('../helpers/traceHelper')
const util = require('../util')
function TraceStepManager (_traceAnalyser) {
this.traceAnalyser = _traceAnalyser
}
TraceStepManager.prototype.isCallInstruction = function (index) {
var state = this.traceAnalyser.trace[index]
const state = this.traceAnalyser.trace[index]
return traceHelper.isCallInstruction(state) && !traceHelper.isCallToPrecompiledContract(index, this.traceAnalyser.trace)
}
TraceStepManager.prototype.isReturnInstruction = function (index) {
var state = this.traceAnalyser.trace[index]
const state = this.traceAnalyser.trace[index]
return traceHelper.isReturnInstruction(state)
}
TraceStepManager.prototype.findStepOverBack = function (currentStep) {
if (this.isReturnInstruction(currentStep)) {
var call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call)
const call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call)
return call.start > 0 ? call.start - 1 : 0
} else {
return currentStep > 0 ? currentStep - 1 : 0
@ -28,7 +28,7 @@ TraceStepManager.prototype.findStepOverBack = function (currentStep) {
TraceStepManager.prototype.findStepOverForward = function (currentStep) {
if (this.isCallInstruction(currentStep)) {
var call = util.findCall(currentStep + 1, this.traceAnalyser.traceCache.callsTree.call)
const call = util.findCall(currentStep + 1, this.traceAnalyser.traceCache.callsTree.call)
return call.return + 1 < this.traceAnalyser.trace.length ? call.return + 1 : this.traceAnalyser.trace.length - 1
} else {
return this.traceAnalyser.trace.length >= currentStep + 1 ? currentStep + 1 : currentStep
@ -36,8 +36,8 @@ TraceStepManager.prototype.findStepOverForward = function (currentStep) {
}
TraceStepManager.prototype.findNextCall = function (currentStep) {
var call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call)
var subCalls = Object.keys(call.calls)
const call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call)
const subCalls = Object.keys(call.calls)
if (subCalls.length) {
var callStart = util.findLowerBound(currentStep, subCalls) + 1
if (subCalls.length > callStart) {
@ -51,7 +51,7 @@ TraceStepManager.prototype.findNextCall = function (currentStep) {
}
TraceStepManager.prototype.findStepOut = function (currentStep) {
var call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call)
const call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call)
return call.return
}

@ -1,5 +1,5 @@
'use strict'
var ethutil = require('ethereumjs-util')
const ethutil = require('ethereumjs-util')
/*
contains misc util: @TODO should be splitted
@ -15,9 +15,9 @@ module.exports = {
ints: IntArray
*/
hexConvert: function (ints) {
var ret = '0x'
for (var i = 0; i < ints.length; i++) {
var h = ints[i]
let ret = '0x'
for (let i = 0; i < ints.length; i++) {
const h = ints[i]
if (h) {
ret += (h <= 0xf ? '0' : '') + h.toString(16)
} else {
@ -34,8 +34,8 @@ module.exports = {
if (hexString.slice(0, 2) === '0x') {
hexString = hexString.slice(2)
}
var integers = []
for (var i = 0; i < hexString.length; i += 2) {
const integers = []
for (let i = 0; i < hexString.length; i += 2) {
integers.push(parseInt(hexString.slice(i, i + 2), 16))
}
return integers
@ -45,9 +45,9 @@ module.exports = {
ints: list of BNs
*/
hexListFromBNs: function (bnList) {
var ret = []
for (var k in bnList) {
var v = bnList[k]
const ret = []
for (let k in bnList) {
const v = bnList[k]
if (ethutil.BN.isBN(v)) {
ret.push('0x' + v.toString('hex', 64))
} else {
@ -61,8 +61,8 @@ module.exports = {
ints: list of IntArrays
*/
hexListConvert: function (intsList) {
var ret = []
for (var k in intsList) {
const ret = []
for (let k in intsList) {
ret.push(this.hexConvert(intsList[k]))
}
return ret
@ -72,10 +72,10 @@ module.exports = {
ints: ints: IntArray
*/
formatMemory: function (mem) {
var hexMem = this.hexConvert(mem).substr(2)
var ret = []
for (var k = 0; k < hexMem.length; k += 32) {
var row = hexMem.substr(k, 32)
const hexMem = this.hexConvert(mem).substr(2)
const ret = []
for (let k = 0; k < hexMem.length; k += 32) {
const row = hexMem.substr(k, 32)
ret.push(row)
}
return ret
@ -87,11 +87,11 @@ module.exports = {
return largest i such that array[i] <= target; return -1 if array[0] > target || array is empty
*/
findLowerBound: function (target, array) {
var start = 0
var length = array.length
let start = 0
let length = array.length
while (length > 0) {
var half = length >> 1
var middle = start + half
const half = length >> 1
const middle = start + half
if (array[middle] <= target) {
length = length - 1 - half
start = middle + 1
@ -108,7 +108,7 @@ module.exports = {
return largest array[i] such that array[i] <= target; return null if array[0] > target || array is empty
*/
findLowerBoundValue: function (target, array) {
var index = this.findLowerBound(target, array)
const index = this.findLowerBound(target, array)
return index >= 0 ? array[index] : null
},
@ -122,13 +122,13 @@ module.exports = {
if (array.length === 0) {
return -1
}
var index = this.findLowerBound(target, array)
const index = this.findLowerBound(target, array)
if (index < 0) {
return 0
} else if (index >= array.length - 1) {
return array.length - 1
} else {
var middle = (array[index] + array[index + 1]) / 2
const middle = (array[index] + array[index + 1]) / 2
return target <= middle ? index : index + 1
}
},
@ -161,7 +161,7 @@ module.exports = {
if (typeof value === 'string' && value.indexOf('0x') !== 0) {
value = '0x' + value
}
var ret = ethutil.bufferToHex(ethutil.setLengthLeft(value, 32))
let ret = ethutil.bufferToHex(ethutil.setLengthLeft(value, 32))
ret = ethutil.keccak(ret)
return ethutil.bufferToHex(ret)
},
@ -218,7 +218,7 @@ module.exports = {
// if code2 is not a library, well we still suppose that the comparison remain relevant even if we remove some information from `code1`
code1 = replaceLibReference(code1, 4)
}
var pos = -1
let pos = -1
while ((pos = code2.search(/__(.*)__/)) !== -1) {
code2 = replaceLibReference(code2, pos)
code1 = replaceLibReference(code1, pos)
@ -240,22 +240,22 @@ function replaceLibReference (code, pos) {
}
function buildCallPath (index, rootCall) {
var ret = []
const ret = []
findCallInternal(index, rootCall, ret)
return ret
}
function findCall (index, rootCall) {
var ret = buildCallPath(index, rootCall)
const ret = buildCallPath(index, rootCall)
return ret[ret.length - 1]
}
function findCallInternal (index, rootCall, callsPath) {
var calls = Object.keys(rootCall.calls)
var ret = rootCall
const calls = Object.keys(rootCall.calls)
const ret = rootCall
callsPath.push(rootCall)
for (var k in calls) {
var subCall = rootCall.calls[calls[k]]
for (let k in calls) {
let subCall = rootCall.calls[calls[k]]
if (index >= subCall.start && index <= subCall.return) {
findCallInternal(index, subCall, callsPath)
break
@ -268,7 +268,7 @@ function findCallInternal (index, rootCall, callsPath) {
function groupBy (arr, key) {
return arr.reduce((sum, item) => {
const groupByVal = item[key]
var groupedItems = sum[groupByVal] || []
const groupedItems = sum[groupByVal] || []
groupedItems.push(item)
sum[groupByVal] = groupedItems
return sum

@ -1,13 +1,12 @@
function dummyProvider () {
var self = this
this.eth = {}
this.debug = {}
this.eth.getCode = function (address, cb) { return self.getCode(address, cb) }
this.eth.getTransaction = function (hash, cb) { return self.getTransaction(hash, cb) }
this.eth.getTransactionFromBlock = function (blockNumber, txIndex, cb) { return self.getTransactionFromBlock(blockNumber, txIndex, cb) }
this.eth.getBlockNumber = function (cb) { return self.getBlockNumber(cb) }
this.debug.traceTransaction = function (hash, options, cb) { return self.traceTransaction(hash, options, cb) }
this.debug.storageRangeAt = function (blockNumber, txIndex, address, start, end, maxLength, cb) { return self.storageRangeAt(blockNumber, txIndex, address, start, end, maxLength, cb) }
this.eth.getCode = (address, cb) => { return this.getCode(address, cb) }
this.eth.getTransaction = (hash, cb) => { return this.getTransaction(hash, cb) }
this.eth.getTransactionFromBlock = (blockNumber, txIndex, cb) => { return this.getTransactionFromBlock(blockNumber, txIndex, cb) }
this.eth.getBlockNumber = (cb) => { return this.getBlockNumber(cb) }
this.debug.traceTransaction = (hash, options, cb) => { return this.traceTransaction(hash, options, cb) }
this.debug.storageRangeAt = (blockNumber, txIndex, address, start, end, maxLength, cb) => { return this.storageRangeAt(blockNumber, txIndex, address, start, end, maxLength, cb) }
this.providers = { 'HttpProvider': function (url) {} }
this.currentProvider = {'host': ''}
}

@ -1,5 +1,5 @@
var Web3VMProvider = require('./web3VmProvider')
var init = require('../init')
const Web3VMProvider = require('./web3VmProvider')
const init = require('../init')
function Web3Providers () {
this.modes = {}
@ -7,7 +7,7 @@ function Web3Providers () {
Web3Providers.prototype.addProvider = function (type, obj) {
if (type === 'INTERNAL') {
var web3 = init.loadWeb3()
const web3 = init.loadWeb3()
this.addWeb3(type, web3)
} else if (type === 'vm') {
this.addVM(type, obj)
@ -30,7 +30,7 @@ Web3Providers.prototype.addWeb3 = function (type, web3) {
}
Web3Providers.prototype.addVM = function (type, vm) {
var vmProvider = new Web3VMProvider()
const vmProvider = new Web3VMProvider()
vmProvider.setVM(vm)
this.modes[type] = vmProvider
}

@ -1,11 +1,10 @@
var util = require('../util')
var uiutil = require('../helpers/uiHelper')
var traceHelper = require('../helpers/traceHelper')
var ethutil = require('ethereumjs-util')
var Web3 = require('web3')
const util = require('../util')
const uiutil = require('../helpers/uiHelper')
const traceHelper = require('../helpers/traceHelper')
const ethutil = require('ethereumjs-util')
const Web3 = require('web3')
function web3VmProvider () {
var self = this
this.web3 = new Web3()
this.vm
this.vmTraces = {}
@ -18,40 +17,48 @@ function web3VmProvider () {
this.incr = 0
this.eth = {}
this.debug = {}
this.eth.getCode = (...args) => self.getCode(...args)
this.eth.getTransaction = (...args) => self.getTransaction(...args)
this.eth.getTransactionReceipt = (...args) => self.getTransactionReceipt(...args)
this.eth.getTransactionFromBlock = (...args) => self.getTransactionFromBlock(...args)
this.eth.getBlockNumber = (...args) => self.getBlockNumber(...args)
this.debug.traceTransaction = (...args) => self.traceTransaction(...args)
this.debug.storageRangeAt = (...args) => self.storageRangeAt(...args)
this.debug.preimage = (...args) => self.preimage(...args)
this.eth.getCode = (...args) => this.getCode(...args)
this.eth.getTransaction = (...args) => this.getTransaction(...args)
this.eth.getTransactionReceipt = (...args) => this.getTransactionReceipt(...args)
this.eth.getTransactionFromBlock = (...args) => this.getTransactionFromBlock(...args)
this.eth.getBlockNumber = (...args) => this.getBlockNumber(...args)
this.debug.traceTransaction = (...args) => this.traceTransaction(...args)
this.debug.storageRangeAt = (...args) => this.storageRangeAt(...args)
this.debug.preimage = (...args) => this.preimage(...args)
this.providers = { 'HttpProvider': function (url) {} }
this.currentProvider = {'host': 'vm provider'}
this.storageCache = {}
this.lastProcessedStorageTxHash = {}
this.sha3Preimages = {}
// util
this.sha3 = (...args) => this.web3.utils.sha3(...args)
this.toHex = (...args) => this.web3.utils.toHex(...args)
this.toAscii = (...args) => this.web3.utils.hexToAscii(...args)
this.fromAscii = (...args) => this.web3.utils.asciiToHex(...args)
this.fromDecimal = (...args) => this.web3.utils.numberToHex(...args)
this.fromWei = (...args) => this.web3.utils.fromWei(...args)
this.toWei = (...args) => this.web3.utils.toWei(...args)
this.toBigNumber = (...args) => this.web3.utils.toBN(...args)
this.isAddress = (...args) => this.web3.utils.isAddress(...args)
this.utils = Web3.utils || []
}
web3VmProvider.prototype.setVM = function (vm) {
if (this.vm === vm) return
var self = this
this.vm = vm
this.vm.on('step', function (data) {
self.pushTrace(self, data)
this.vm.on('step', (data) => {
this.pushTrace(this, data)
})
this.vm.on('afterTx', function (data) {
self.txProcessed(self, data)
this.vm.on('afterTx', (data) => {
this.txProcessed(this, data)
})
this.vm.on('beforeTx', function (data) {
self.txWillProcess(self, data)
this.vm.on('beforeTx', (data) => {
this.txWillProcess(this, data)
})
}
web3VmProvider.prototype.releaseCurrentHash = function () {
var ret = this.processingHash
const ret = this.processingHash
this.processingHash = undefined
return ret
}
@ -64,7 +71,7 @@ web3VmProvider.prototype.txWillProcess = function (self, data) {
return: '0x0',
structLogs: []
}
var tx = {}
let tx = {}
tx.hash = self.processingHash
tx.from = util.hexConvert(data.getSenderAddress())
if (data.to && data.to.length) {
@ -82,7 +89,7 @@ web3VmProvider.prototype.txWillProcess = function (self, data) {
self.storageCache[self.processingHash] = {}
if (tx.to) {
const account = ethutil.toBuffer(tx.to)
self.vm.stateManager.dumpStorage(account, function (storage) {
self.vm.stateManager.dumpStorage(account, (storage) => {
self.storageCache[self.processingHash][tx.to] = storage
self.lastProcessedStorageTxHash[tx.to] = self.processingHash
})
@ -91,16 +98,16 @@ web3VmProvider.prototype.txWillProcess = function (self, data) {
}
web3VmProvider.prototype.txProcessed = function (self, data) {
var lastOp = self.vmTraces[self.processingHash].structLogs[self.processingIndex - 1]
const lastOp = self.vmTraces[self.processingHash].structLogs[self.processingIndex - 1]
if (lastOp) {
lastOp.error = lastOp.op !== 'RETURN' && lastOp.op !== 'STOP' && lastOp.op !== 'SELFDESTRUCT'
}
self.vmTraces[self.processingHash].gas = '0x' + data.gasUsed.toString(16)
var logs = []
for (var l in data.execResult.logs) {
var log = data.execResult.logs[l]
var topics = []
const logs = []
for (let l in data.execResult.logs) {
const log = data.execResult.logs[l]
const topics = []
if (log[1].length > 0) {
for (var k in log[1]) {
topics.push('0x' + log[1][k].toString('hex'))
@ -121,7 +128,7 @@ web3VmProvider.prototype.txProcessed = function (self, data) {
self.txsReceipt[self.processingHash].status = `0x${status}`
if (data.createdAddress) {
var address = util.hexConvert(data.createdAddress)
const address = util.hexConvert(data.createdAddress)
self.vmTraces[self.processingHash].return = address
self.txsReceipt[self.processingHash].contractAddress = address
} else if (data.execResult.returnValue) {
@ -135,12 +142,12 @@ web3VmProvider.prototype.txProcessed = function (self, data) {
}
web3VmProvider.prototype.pushTrace = function (self, data) {
var depth = data.depth + 1 // geth starts the depth from 1
const depth = data.depth + 1 // geth starts the depth from 1
if (!self.processingHash) {
console.log('no tx processing')
return
}
var previousopcode
let previousopcode
if (self.vmTraces[self.processingHash] && self.vmTraces[self.processingHash].structLogs[this.processingIndex - 1]) {
previousopcode = self.vmTraces[self.processingHash].structLogs[this.processingIndex - 1]
}
@ -149,7 +156,7 @@ web3VmProvider.prototype.pushTrace = function (self, data) {
// returning from context, set error it is not STOP, RETURN
previousopcode.invalidDepthChange = previousopcode.op !== 'RETURN' && previousopcode.op !== 'STOP'
}
var step = {
const step = {
stack: util.hexListFromBNs(data.stack),
memory: util.formatMemory(data.memory),
storage: data.storage,
@ -178,8 +185,8 @@ web3VmProvider.prototype.pushTrace = function (self, data) {
}
}
if (previousopcode && traceHelper.isSHA3Instruction(previousopcode)) {
var preimage = getSha3Input(previousopcode.stack, previousopcode.memory)
var imageHash = step.stack[step.stack.length - 1].replace('0x', '')
const preimage = getSha3Input(previousopcode.stack, previousopcode.memory)
const imageHash = step.stack[step.stack.length - 1].replace('0x', '')
self.sha3Preimages[imageHash] = {
'preimage': preimage
}
@ -191,7 +198,7 @@ web3VmProvider.prototype.pushTrace = function (self, data) {
web3VmProvider.prototype.getCode = function (address, cb) {
const account = ethutil.toBuffer(address)
this.vm.stateManager.getContractCode(account, function (error, result) {
this.vm.stateManager.getContractCode(account, (error, result) => {
cb(error, util.hexConvert(result))
})
}
@ -219,7 +226,7 @@ web3VmProvider.prototype.storageRangeAt = function (blockNumber, txIndex, addres
}
if (this.storageCache[txIndex] && this.storageCache[txIndex][address]) {
var storage = this.storageCache[txIndex][address]
const storage = this.storageCache[txIndex][address]
return cb(null, {
storage: JSON.parse(JSON.stringify(storage)),
nextKey: null
@ -259,7 +266,7 @@ web3VmProvider.prototype.getTransactionReceipt = function (txHash, cb) {
}
web3VmProvider.prototype.getTransactionFromBlock = function (blockNumber, txIndex, cb) {
var mes = 'not supposed to be needed by remix in vmmode'
const mes = 'not supposed to be needed by remix in vmmode'
console.log(mes)
if (cb) {
cb(mes, null)
@ -272,26 +279,26 @@ web3VmProvider.prototype.preimage = function (hashedKey, cb) {
}
function getSha3Input (stack, memory) {
var memoryStart = stack[stack.length - 1]
var memoryLength = stack[stack.length - 2]
var memStartDec = (new ethutil.BN(memoryStart.replace('0x', ''), 16)).toString(10)
let memoryStart = stack[stack.length - 1]
let memoryLength = stack[stack.length - 2]
const memStartDec = (new ethutil.BN(memoryStart.replace('0x', ''), 16)).toString(10)
memoryStart = parseInt(memStartDec) * 2
var memLengthDec = (new ethutil.BN(memoryLength.replace('0x', ''), 16).toString(10))
const memLengthDec = (new ethutil.BN(memoryLength.replace('0x', ''), 16).toString(10))
memoryLength = parseInt(memLengthDec) * 2
var i = Math.floor(memoryStart / 32)
var maxIndex = Math.floor(memoryLength / 32) + i
let i = Math.floor(memoryStart / 32)
const maxIndex = Math.floor(memoryLength / 32) + i
if (!memory[i]) {
return emptyFill(memoryLength)
}
var sha3Input = memory[i].slice(memoryStart - 32 * i)
let sha3Input = memory[i].slice(memoryStart - 32 * i)
i++
while (i < maxIndex) {
sha3Input += memory[i] ? memory[i] : emptyFill(32)
i++
}
if (sha3Input.length < memoryLength) {
var leftSize = memoryLength - sha3Input.length
const leftSize = memoryLength - sha3Input.length
sha3Input += memory[i] ? memory[i].slice(0, leftSize) : emptyFill(leftSize)
}
return sha3Input

@ -1,12 +1,12 @@
'use strict'
var tape = require('tape')
var AstWalker = require('../src/astWalker')
var node = require('./resources/ast')
const tape = require('tape')
const AstWalker = require('../src/astWalker')
const node = require('./resources/ast')
tape('ASTWalker', function (t) {
t.test('ASTWalker.walk', function (st) {
st.plan(24)
var astwalker = new AstWalker()
const astwalker = new AstWalker()
astwalker.walk(node.ast.legacyAST, function (node) {
if (node.name === 'ContractDefinition') {
@ -18,7 +18,7 @@ tape('ASTWalker', function (t) {
return true
})
var callback = {}
const callback = {}
callback.FunctionDefinition = function (node) {
st.equal(node.name, 'FunctionDefinition')
st.equal(node.attributes.name === 'set' || node.attributes.name === 'get', true)

@ -1,28 +1,28 @@
'use strict'
var tape = require('tape')
var Web3Providers = require('../src/web3Provider/web3Providers')
var TraceManager = require('../src/trace/traceManager')
var CodeManager = require('../src/code/codeManager')
var web3Test = require('./resources/testWeb3')
const tape = require('tape')
const Web3Providers = require('../src/web3Provider/web3Providers')
const TraceManager = require('../src/trace/traceManager')
const CodeManager = require('../src/code/codeManager')
const web3Test = require('./resources/testWeb3')
let web3 = null
tape('CodeManager', function (t) {
var codeManager
var web3Providers = new Web3Providers()
let codeManager
const web3Providers = new Web3Providers()
web3Providers.addProvider('TEST', web3Test)
web3Providers.get('TEST', function (error, obj) {
if (error) {
var mes = 'provider TEST not defined'
const mes = 'provider TEST not defined'
console.log(mes)
t.fail(mes)
} else {
web3 = obj
var traceManager = new TraceManager({web3: web3})
const traceManager = new TraceManager({web3: web3})
codeManager = new CodeManager(traceManager)
var contractCode = web3.eth.getCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5')
const contractCode = web3.eth.getCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5')
codeManager.codeResolver.cacheExecutingCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', contractCode) // so a call to web3 is not necessary
var tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51')
const tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51')
traceManager.resolveTrace(tx, function (error, result) {
if (error) {
t.fail(' - traceManager.resolveTrace - failed ' + result)
@ -63,7 +63,7 @@ function continueTesting (t, codeManager) {
}
}
})
var tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51')
const tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51')
codeManager.resolveStep(0, tx)
codeManager.resolveStep(70, tx)
})

@ -1,7 +1,7 @@
'use strict'
var tape = require('tape')
var disassemble = require('../src/code/disassembler').disassemble
const tape = require('tape')
const disassemble = require('../src/code/disassembler').disassemble
tape('Disassembler', function (t) {
t.test('empty', function (st) {
@ -18,8 +18,8 @@ tape('Disassembler', function (t) {
})
t.test('complexcode', function (st) {
st.plan(1)
var code = '60606040526009600060005055607e8060186000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480630dbe671f146039576035565b6002565b3460025760486004805050604a565b005b6000600090505b600a811015607a5760006000818150548092919060010191905055505b80806001019150506051565b5b5056'
var asm = `mstore(0x40, 0x60)
const code = '60606040526009600060005055607e8060186000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480630dbe671f146039576035565b6002565b3460025760486004805050604a565b005b6000600090505b600a811015607a5760006000818150548092919060010191905055505b80806001019150506051565b5b5056'
const asm = `mstore(0x40, 0x60)
0x09
0x00
pop(0x00)

@ -1,16 +1,16 @@
'use strict'
var tape = require('tape')
var EventManager = require('../src/eventManager')
const tape = require('tape')
const EventManager = require('../src/eventManager')
tape('eventManager', function (t) {
t.test('eventManager', function (st) {
var events = new EventManager()
var listenner = {}
const events = new EventManager()
const listenner = {}
var trace = ''
let trace = ''
listenner.listen = function (data1) {
trace += data1
}
var registeredFunction = function (data) {
const registeredFunction = function (data) {
trace += data
}
events.register('event1', listenner, listenner.listen)

@ -9,7 +9,7 @@ var init = {
},
readFile: function (filename, callback) {
var fs = require('fs')
const fs = require('fs')
try {
console.log('reading ' + filename)
if (callback) {

@ -1,4 +1,4 @@
var node = {}
const node = {}
node.ast = {"legacyAST":{"children":[{"attributes":{"fullyImplemented":true,"isLibrary":false,"linearizedBaseContracts":[5640396],"name":"test"},"children":[{"attributes":{"name":"x","type":"int256"},"children":[{"attributes":{"name":"int"},"id":5657860,"name":"ElementaryTypeName","src":"21:3:11"}],"id":5658100,"name":"VariableDeclaration","src":"21:5:11"},{"attributes":{"name":"y","type":"int256"},"children":[{"attributes":{"name":"int"},"id":5658180,"name":"ElementaryTypeName","src":"38:3:11"}],"id":5658268,"name":"VariableDeclaration","src":"38:5:11"},{"attributes":{"constant":false,"name":"set","public":true},"children":[{"children":[{"attributes":{"name":"_x","type":"int256"},"children":[{"attributes":{"name":"int"},"id":5658404,"name":"ElementaryTypeName","src":"68:3:11"}],"id":5658492,"name":"VariableDeclaration","src":"68:6:11"}],"id":5658572,"name":"ParameterList","src":"67:8:11"},{"children":[{"attributes":{"name":"_r","type":"int256"},"children":[{"attributes":{"name":"int"},"id":5658628,"name":"ElementaryTypeName","src":"85:3:11"}],"id":5658716,"name":"VariableDeclaration","src":"85:6:11"}],"id":5658796,"name":"ParameterList","src":"84:8:11"},{"children":[{"children":[{"attributes":{"operator":"=","type":"int256"},"children":[{"attributes":{"type":"int256","value":"x"},"id":5658900,"name":"Identifier","src":"108:1:11"},{"attributes":{"type":"int256","value":"_x"},"id":5658980,"name":"Identifier","src":"112:2:11"}],"id":5657492,"name":"Assignment","src":"108:6:11"}],"id":5659028,"name":"ExpressionStatement","src":"108:6:11"},{"children":[{"attributes":{"operator":"=","type":"int256"},"children":[{"attributes":{"type":"int256","value":"y"},"id":5659116,"name":"Identifier","src":"125:1:11"},{"attributes":{"string":null,"type":"int_const 10","value":"10"},"id":5659196,"name":"Literal","src":"129:2:11"}],"id":5659252,"name":"Assignment","src":"125:6:11"}],"id":5659316,"name":"ExpressionStatement","src":"125:6:11"},{"children":[{"attributes":{"operator":"=","type":"int256"},"children":[{"attributes":{"type":"int256","value":"_r"},"id":5659428,"name":"Identifier","src":"141:2:11"},{"attributes":{"type":"int256","value":"x"},"id":5639308,"name":"Identifier","src":"146:1:11"}],"id":5639356,"name":"Assignment","src":"141:6:11"}],"id":5639420,"name":"ExpressionStatement","src":"141:6:11"}],"id":5639516,"name":"Block","src":"97:57:11"}],"id":5639612,"name":"FunctionDefinition","src":"55:99:11"},{"attributes":{"constant":false,"name":"get","public":true},"children":[{"children":[],"id":5639764,"name":"ParameterList","src":"179:2:11"},{"children":[{"attributes":{"name":"x","type":"uint256"},"children":[{"attributes":{"name":"uint"},"id":5639820,"name":"ElementaryTypeName","src":"191:4:11"}],"id":5639908,"name":"VariableDeclaration","src":"191:6:11"},{"attributes":{"name":"y","type":"uint256"},"children":[{"attributes":{"name":"uint"},"id":5639988,"name":"ElementaryTypeName","src":"199:4:11"}],"id":5640076,"name":"VariableDeclaration","src":"199:6:11"}],"id":5640156,"name":"ParameterList","src":"190:16:11"},{"children":[],"id":5640212,"name":"Block","src":"212:17:11"}],"id":5640276,"name":"FunctionDefinition","src":"167:62:11"}],"id":5640396,"name":"ContractDefinition","src":"0:231:11"}],"name":"SourceUnit"}}

@ -1,4 +1,4 @@
var sourceRuntimeMapping = {}
const sourceRuntimeMapping = {}
sourceRuntimeMapping.mapping = '0:205:4:-;;;;;;;;;;;;;;;;;;;;;;55:74;;;;;;;;;;;;;;;;;;;;;;;;;;142:61;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;55:74;103:2;99:1;;:6;;;;;120:2;116:1;;:6;;;;;55:74;;;:::o;142:61::-;166:6;174;142:61;;;:::o'
sourceRuntimeMapping.source = `contract test {
int x;

@ -1,9 +1,9 @@
'use strict'
var init = require('../init')
var web3Override = {}
const init = require('../init')
const web3Override = {}
web3Override.eth = {}
web3Override.debug = {}
var data = init.readFile(require('path').resolve(__dirname, 'testWeb3.json'))
let data = init.readFile(require('path').resolve(__dirname, 'testWeb3.json'))
data = JSON.parse(data)
web3Override.eth.getCode = function (address, callback) {

@ -1,16 +1,16 @@
'use strict'
var tape = require('tape')
var sourceMapping = require('./resources/sourceMapping')
var SourceMappingDecoder = require('../src/sourceMappingDecoder')
var compiler = require('solc')
var compilerInput = require('../src/helpers/compilerHelper').compilerInput
const tape = require('tape')
const sourceMapping = require('./resources/sourceMapping')
const SourceMappingDecoder = require('../src/sourceMappingDecoder')
const compiler = require('solc')
const compilerInput = require('../src/helpers/compilerHelper').compilerInput
tape('SourceMappingDecoder', function (t) {
t.test('SourceMappingDecoder.findNodeAtInstructionIndex', function (st) {
var output = compiler.compile(compilerInput(contracts))
let output = compiler.compile(compilerInput(contracts))
output = JSON.parse(output)
var sourceMappingDecoder = new SourceMappingDecoder()
var node = sourceMappingDecoder.findNodeAtInstructionIndex('FunctionDefinition', 2, output.contracts['test.sol']['test'].evm.deployedBytecode.sourceMap, output.sources['test.sol'])
const sourceMappingDecoder = new SourceMappingDecoder()
let node = sourceMappingDecoder.findNodeAtInstructionIndex('FunctionDefinition', 2, output.contracts['test.sol']['test'].evm.deployedBytecode.sourceMap, output.sources['test.sol'])
st.equal(node, null)
node = sourceMappingDecoder.findNodeAtInstructionIndex('FunctionDefinition', 80, output.contracts['test.sol']['test'].evm.deployedBytecode.sourceMap, output.sources['test.sol'])
st.notEqual(node, null)
@ -20,12 +20,12 @@ tape('SourceMappingDecoder', function (t) {
st.end()
})
var testSourceMapping = {}
const testSourceMapping = {}
t.test('sourceMappingDecoder', function (st) {
st.plan(28)
var sourceMappingDecoder = new SourceMappingDecoder()
const sourceMappingDecoder = new SourceMappingDecoder()
console.log('test decompressAll')
var result = sourceMappingDecoder.decompressAll(sourceMapping.mapping)
let result = sourceMappingDecoder.decompressAll(sourceMapping.mapping)
st.equal(result[0].start, 0)
st.equal(result[0].length, 205)
st.equal(result[0].file, 4)
@ -42,7 +42,7 @@ tape('SourceMappingDecoder', function (t) {
st.equal(result[22].file, 4)
st.equal(result[22].jump, '-')
var last = result.length - 1
const last = result.length - 1
st.equal(result[last].start, 142)
st.equal(result[last].length, 61)
st.equal(result[last].file, 4)
@ -77,11 +77,11 @@ tape('SourceMappingDecoder', function (t) {
t.test('sourceMappingLineColumnConverter', function (st) {
st.plan(14)
var sourceMappingDecoder = new SourceMappingDecoder()
var linesbreak = sourceMappingDecoder.getLinebreakPositions(sourceMapping.source)
const sourceMappingDecoder = new SourceMappingDecoder()
const linesbreak = sourceMappingDecoder.getLinebreakPositions(sourceMapping.source)
st.equal(linesbreak[0], 16)
st.equal(linesbreak[5], 84)
var result = sourceMappingDecoder.convertOffsetToLineColumn(testSourceMapping[21], linesbreak)
let result = sourceMappingDecoder.convertOffsetToLineColumn(testSourceMapping[21], linesbreak)
st.equal(result.start.line, 0)
st.equal(result.start.column, 0)
st.equal(result.end.line, 15)
@ -92,7 +92,7 @@ tape('SourceMappingDecoder', function (t) {
st.equal(result.end.line, 7)
st.equal(result.end.column, 14)
var res = { // point to \n
const res = { // point to \n
start: 103,
length: 4,
file: 4,
@ -106,7 +106,7 @@ tape('SourceMappingDecoder', function (t) {
})
})
var contracts = `contract test {
const contracts = `contract test {
function f1() public returns (uint) {
uint t = 4;
return t;

@ -1,20 +1,20 @@
'use strict'
var TraceManager = require('../src/trace/traceManager')
var tape = require('tape')
var Web3Providers = require('../src/web3Provider/web3Providers')
var web3Test = require('./resources/testWeb3')
const TraceManager = require('../src/trace/traceManager')
const tape = require('tape')
const Web3Providers = require('../src/web3Provider/web3Providers')
const web3Test = require('./resources/testWeb3')
let web3 = null
tape('TraceManager', function (t) {
var traceManager
let traceManager
t.test('TraceManager.init', function (st) {
var web3Providers = new Web3Providers()
const web3Providers = new Web3Providers()
web3Providers.addProvider('TEST', web3Test)
web3Providers.get('TEST', function (error, obj) {
if (error) {
var mes = 'provider TEST not defined'
const mes = 'provider TEST not defined'
console.log(mes)
st.fail(mes)
} else {
@ -26,7 +26,7 @@ tape('TraceManager', function (t) {
})
t.test('TraceManager.resolveTrace', function (st) {
var tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51')
const tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51')
traceManager.resolveTrace(tx, function (error, result) {
if (error) {
st.fail(' - traceManager.resolveTrace - failed ' + result)
@ -275,21 +275,21 @@ tape('TraceManager', function (t) {
})
t.test('TraceManager.findStepOverBack', function (st) {
var result = traceManager.findStepOverBack(116)
const result = traceManager.findStepOverBack(116)
console.log(result)
st.ok(result === 115)
st.end()
})
t.test('TraceManager.findStepOverForward', function (st) {
var result = traceManager.findStepOverForward(66)
const result = traceManager.findStepOverForward(66)
console.log(result)
st.ok(result === 67)
st.end()
})
t.test('TraceManager.findNextCall', function (st) {
var result = traceManager.findNextCall(10)
const result = traceManager.findNextCall(10)
console.log(result)
st.ok(result === 63)
st.end()

@ -1,12 +1,12 @@
'use strict'
var tape = require('tape')
var txFormat = require('../src/execution/txFormat')
var txHelper = require('../src/execution/txHelper')
var util = require('../src/util')
var compiler = require('solc')
var compilerInput = require('../src/helpers/compilerHelper').compilerInput
var executionContext = require('../src/execution/execution-context')
var solidityVersion = 'v0.6.0+commit.26b70077'
const tape = require('tape')
const txFormat = require('../src/execution/txFormat')
const txHelper = require('../src/execution/txHelper')
const util = require('../src/util')
let compiler = require('solc')
const compilerInput = require('../src/helpers/compilerHelper').compilerInput
const executionContext = require('../src/execution/execution-context')
const solidityVersion = 'v0.6.0+commit.26b70077'
/* tape *********************************************************** */
tape('load compiler ' + solidityVersion, function (t) {
@ -18,11 +18,11 @@ tape('load compiler ' + solidityVersion, function (t) {
})
})
var context
let context
tape('ContractParameters - (TxFormat.buildData) - format input parameters', function (t) {
var output = compiler.compile(compilerInput(uintContract))
let output = compiler.compile(compilerInput(uintContract))
output = JSON.parse(output)
var contract = output.contracts['test.sol']['uintContractTest']
const contract = output.contracts['test.sol']['uintContractTest']
context = { output, contract }
t.test('(TxFormat.buildData)', function (st) {
@ -48,9 +48,9 @@ function testWithInput (st, params, expected) {
tape('ContractStringParameters - (TxFormat.buildData) - format string input parameters', function (t) {
var output = compiler.compile(compilerInput(stringContract))
let output = compiler.compile(compilerInput(stringContract))
output = JSON.parse(output)
var contract = output.contracts['test.sol']['stringContractTest']
const contract = output.contracts['test.sol']['stringContractTest']
context = { output, contract }
t.test('(TxFormat.buildData)', function (st) {
st.plan(3)
@ -74,9 +74,9 @@ function testWithStringInput (st, params, expected) {
}
tape('ContractArrayParameters - (TxFormat.buildData) - format array input parameters', function (t) {
var output = compiler.compile(compilerInput(arrayContract))
let output = compiler.compile(compilerInput(arrayContract))
output = JSON.parse(output)
var contract = output.contracts['test.sol']['arrayContractTest']
const contract = output.contracts['test.sol']['arrayContractTest']
context = { output, contract }
t.test('(TxFormat.buildData)', function (st) {
st.plan(3)
@ -100,9 +100,9 @@ function testWithArrayInput (st, params, expected) {
}
tape('ContractNestedArrayParameters - (TxFormat.buildData) - format nested array input parameters', function (t) {
var output = compiler.compile(compilerInput(nestedArrayContract))
let output = compiler.compile(compilerInput(nestedArrayContract))
output = JSON.parse(output)
var contract = output.contracts['test.sol']['nestedArrayContractTest']
let contract = output.contracts['test.sol']['nestedArrayContractTest']
context = { output, contract }
t.test('(TxFormat.buildData)', function (st) {
st.plan(2)
@ -129,14 +129,14 @@ function testWithNestedArrayInput (st, params, expected) {
tape('ContractParameters - (TxFormat.buildData) - link Libraries', function (t) {
executionContext.setContext('vm')
var compileData = compiler.compile(compilerInput(deploySimpleLib))
const compileData = compiler.compile(compilerInput(deploySimpleLib))
var fakeDeployedContracts = {
const fakeDeployedContracts = {
lib1: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e11',
lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e33',
testContractLinkLibrary: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e22'
}
var callbackDeployLibraries = (param, callback) => {
const callbackDeployLibraries = (param, callback) => {
callback(null, {
result: {
createdAddress: fakeDeployedContracts[param.data.contractName]
@ -146,29 +146,29 @@ tape('ContractParameters - (TxFormat.buildData) - link Libraries', function (t)
t.test('(TxFormat.buildData and link library (standard way))', function (st) {
st.plan(6)
var output = JSON.parse(compileData)
var contract = output.contracts['test.sol']['testContractLinkLibrary']
const output = JSON.parse(compileData)
const contract = output.contracts['test.sol']['testContractLinkLibrary']
context = { output, contract }
testLinkLibrary(st, fakeDeployedContracts, callbackDeployLibraries)
})
t.test('(TxFormat.encodeConstructorCallAndLinkLibraries and link library (standard way))', function (st) {
st.plan(12)
var output = JSON.parse(compileData)
var contract = output.contracts['test.sol']['testContractLinkLibrary']
const output = JSON.parse(compileData)
const contract = output.contracts['test.sol']['testContractLinkLibrary']
context = { output, contract }
testLinkLibrary2(st, callbackDeployLibraries)
})
})
function testLinkLibrary (st, fakeDeployedContracts, callbackDeployLibraries) {
var deployMsg = ['creation of library test.sol:lib1 pending...',
const deployMsg = ['creation of library test.sol:lib1 pending...',
'creation of library test.sol:lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2 pending...']
txFormat.buildData('testContractLinkLibrary', context.contract, context.output.contracts, true, context.contract.abi[0], '', (error, data) => {
if (error) { return st.fails(error) }
console.log(data)
var linkedbyteCode = data.dataHex
var libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1']
const linkedbyteCode = data.dataHex
let libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1']
st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), fakeDeployedContracts['lib1'].replace('0x', ''))
st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), fakeDeployedContracts['lib1'].replace('0x', ''))
@ -182,22 +182,22 @@ function testLinkLibrary (st, fakeDeployedContracts, callbackDeployLibraries) {
}
function testLinkLibrary2 (st, callbackDeployLibraries) {
var librariesReference = {
const librariesReference = {
'test.sol': {
'lib1': '0xf7a10e525d4b168f45f74db1b61f63d3e7619e11',
'lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2': '0xf7a10e525d4b168f45f74db1b61f63d3e7619e33'
}
}
var data = '608060405234801561001057600080fd5b506101e2806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c80636d4ce63c14610030575b600080fd5b61003861003a565b005b73f7a10e525d4b168f45f74db1b61f63d3e7619e116344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561007e57600080fd5b505af4158015610092573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e336344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b1580156100da57600080fd5b505af41580156100ee573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e336344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561013657600080fd5b505af415801561014a573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e116344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561019257600080fd5b505af41580156101a6573d6000803e3d6000fd5b5050505056fea264697066735822122007784c53df7f324243100f6642d889a08a88831c3811dd13eebe3163b7eb2e5464736f6c63430006000033'
const data = '608060405234801561001057600080fd5b506101e2806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c80636d4ce63c14610030575b600080fd5b61003861003a565b005b73f7a10e525d4b168f45f74db1b61f63d3e7619e116344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561007e57600080fd5b505af4158015610092573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e336344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b1580156100da57600080fd5b505af41580156100ee573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e336344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561013657600080fd5b505af415801561014a573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e116344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561019257600080fd5b505af41580156101a6573d6000803e3d6000fd5b5050505056fea264697066735822122007784c53df7f324243100f6642d889a08a88831c3811dd13eebe3163b7eb2e5464736f6c63430006000033'
var deployMsg = ['creation of library test.sol:lib1 pending...',
const deployMsg = ['creation of library test.sol:lib1 pending...',
'creation of library test.sol:lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2 pending...']
txFormat.encodeConstructorCallAndLinkLibraries(context.contract, '', context.contract.abi[0], librariesReference, context.contract.evm.bytecode.linkReferences, (error, result) => {
console.log(error, result)
st.equal(data, result.dataHex)
var linkedbyteCode = result.dataHex
var libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1']
const linkedbyteCode = result.dataHex
let libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1']
st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), librariesReference['test.sol']['lib1'].replace('0x', ''))
st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), librariesReference['test.sol']['lib1'].replace('0x', ''))
libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2']
@ -208,8 +208,8 @@ function testLinkLibrary2 (st, callbackDeployLibraries) {
txFormat.encodeConstructorCallAndDeployLibraries('testContractLinkLibrary', context.contract, context.output.contracts, '', context.contract.abi[0], (error, result) => {
console.log(error, result)
st.equal(data, result.dataHex)
var linkedbyteCode = result.dataHex
var libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1']
const linkedbyteCode = result.dataHex
let libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1']
st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), librariesReference['test.sol']['lib1'].replace('0x', ''))
st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), librariesReference['test.sol']['lib1'].replace('0x', ''))
@ -232,9 +232,9 @@ tape('EncodeParameter', function (t) {
})
function encodeFunctionCallTest (st) {
var output = compiler.compile(compilerInput(encodeFunctionCall))
let output = compiler.compile(compilerInput(encodeFunctionCall))
output = JSON.parse(output)
var contract = output.contracts['test.sol']['testContractLinkLibrary']
const contract = output.contracts['test.sol']['testContractLinkLibrary']
txFormat.encodeFunctionCall('123, "test string"', contract.abi[0], (error, encoded) => {
console.log(error)
st.equal(encoded.dataHex, '0x805da4ad000000000000000000000000000000000000000000000000000000000000007b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b7465737420737472696e67000000000000000000000000000000000000000000')
@ -246,31 +246,31 @@ function encodeFunctionCallTest (st) {
tape('test fallback function', function (t) {
t.test('(fallback)', function (st) {
st.plan(2)
var output = compiler.compile(compilerInput(fallbackFunction))
let output = compiler.compile(compilerInput(fallbackFunction))
output = JSON.parse(output)
var contract = output.contracts['test.sol']['fallbackFunctionContract']
const contract = output.contracts['test.sol']['fallbackFunctionContract']
st.equal(txHelper.encodeFunctionId(contract.abi[1]), '0x805da4ad')
st.equal(txHelper.encodeFunctionId(contract.abi[0]), '0x')
})
})
tape('test abiEncoderV2', function (t) {
var functionId = '0x56d89238'
var encodedData = '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000170000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000042ed123b0bd8203c2700000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000090746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f00000000000000000000000000000000'
var value1 = '1'
var value2 = '1234567890123456789543'
var value3 = 'test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_'
var decodedData = `[${value1}, ${value2}, "${value3}"], 23`
const functionId = '0x56d89238'
const encodedData = '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000170000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000042ed123b0bd8203c2700000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000090746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f00000000000000000000000000000000'
const value1 = '1'
const value2 = '1234567890123456789543'
const value3 = 'test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_'
const decodedData = `[${value1}, ${value2}, "${value3}"], 23`
t.test('(abiEncoderV2)', function (st) {
st.plan(2)
var output = compiler.compile(compilerInput(abiEncoderV2))
let output = compiler.compile(compilerInput(abiEncoderV2))
output = JSON.parse(output)
var contract = output.contracts['test.sol']['test']
let contract = output.contracts['test.sol']['test']
txFormat.encodeFunctionCall(decodedData, contract.abi[0], (error, encoded) => {
console.log(error)
st.equal(encoded.dataHex, functionId + encodedData.replace('0x', ''))
})
var decoded = txFormat.decodeResponse(util.hexToIntArray(encodedData), contract.abi[0])
let decoded = txFormat.decodeResponse(util.hexToIntArray(encodedData), contract.abi[0])
console.log(decoded)
st.equal(decoded[0], `tuple(uint256,uint256,string): ${value1},${value2},${value3}`)
})
@ -286,26 +286,26 @@ tape('test abiEncoderV2 array of tuple', function (t) {
*/
st.plan(2)
var output = compiler.compile(compilerInput(abiEncoderV2ArrayOfTuple))
let output = compiler.compile(compilerInput(abiEncoderV2ArrayOfTuple))
output = JSON.parse(output)
var contract = output.contracts['test.sol']['test']
const contract = output.contracts['test.sol']['test']
txFormat.encodeParams('[34, "test"]', contract.abi[1], (error, encoded) => {
console.log(error)
var decoded = txFormat.decodeResponse(util.hexToIntArray(encoded.dataHex), contract.abi[1])
const decoded = txFormat.decodeResponse(util.hexToIntArray(encoded.dataHex), contract.abi[1])
console.log(decoded)
st.equal(decoded[0], 'tuple(uint256,string): _strucmts 34,test')
})
txFormat.encodeParams('[[34, "test"], [123, "test2"]]', contract.abi[2], (error, encoded) => {
console.log(error)
var decoded = txFormat.decodeResponse(util.hexToIntArray(encoded.dataHex), contract.abi[2])
const decoded = txFormat.decodeResponse(util.hexToIntArray(encoded.dataHex), contract.abi[2])
console.log(decoded)
st.equal(decoded[0], 'tuple(uint256,string)[]: strucmts 34,test,123,test2')
})
})
})
var uintContract = `contract uintContractTest {
const uintContract = `contract uintContractTest {
uint _tp;
address _ap;
function test(uint _t, address _a, uint _i) public {
@ -314,7 +314,7 @@ var uintContract = `contract uintContractTest {
}
}`
var stringContract = `contract stringContractTest {
const stringContract = `contract stringContractTest {
string _tp;
address _ap;
function test(string memory _t, address _a, string memory _i) public {
@ -323,7 +323,7 @@ var stringContract = `contract stringContractTest {
}
}`
var arrayContract = `contract arrayContractTest {
const arrayContract = `contract arrayContractTest {
string _sp;
address _ap;
uint _up;
@ -339,7 +339,7 @@ var arrayContract = `contract arrayContractTest {
}
}`
var nestedArrayContract = `contract nestedArrayContractTest {
const nestedArrayContract = `contract nestedArrayContractTest {
uint public co;
string public str;
bool public b1;
@ -353,7 +353,7 @@ var nestedArrayContract = `contract nestedArrayContractTest {
}
}`
var deploySimpleLib = `pragma solidity >= 0.5.0 < 0.7.0;
const deploySimpleLib = `pragma solidity >= 0.5.0 < 0.7.0;
library lib1 {
function getEmpty () public {
@ -374,14 +374,14 @@ contract testContractLinkLibrary {
}
}`
var encodeFunctionCall = `pragma solidity >= 0.5.0 < 0.7.0;
const encodeFunctionCall = `pragma solidity >= 0.5.0 < 0.7.0;
contract testContractLinkLibrary {
function get (uint _p, string memory _o) public {
}
}`
var fallbackFunction = `pragma solidity >= 0.5.0 < 0.7.0;
const fallbackFunction = `pragma solidity >= 0.5.0 < 0.7.0;
contract fallbackFunctionContract {
function get (uint _p, string memory _o) public {
@ -390,7 +390,7 @@ contract fallbackFunctionContract {
fallback () external {}
}`
var abiEncoderV2 = `pragma experimental ABIEncoderV2;
const abiEncoderV2 = `pragma experimental ABIEncoderV2;
contract test {
struct p {
@ -410,7 +410,7 @@ contract test {
}
}`
var abiEncoderV2ArrayOfTuple = `pragma experimental ABIEncoderV2;
const abiEncoderV2ArrayOfTuple = `pragma experimental ABIEncoderV2;
contract test {
struct MyStruct {uint256 num; string _string;}

@ -1,10 +1,10 @@
'use strict'
var tape = require('tape')
var txHelper = require('../src/execution/txHelper')
const tape = require('tape')
const txHelper = require('../src/execution/txHelper')
tape('getFunction', function (st) {
st.plan(5)
var fn = txHelper.getFunction(JSON.parse(abi), 'o((address,uint256))')
let fn = txHelper.getFunction(JSON.parse(abi), 'o((address,uint256))')
st.equal(fn.name, 'o')
fn = txHelper.getFunction(JSON.parse(abi), 'i(bytes32)')
@ -20,7 +20,7 @@ tape('getFunction', function (st) {
st.equal(fn.type, 'fallback')
})
var abi = `[
const abi = `[
{
"constant": false,
"inputs": [

@ -1,12 +1,12 @@
'use strict'
var tape = require('tape')
var util = require('../src/util')
const tape = require('tape')
const util = require('../src/util')
tape('Util', function (t) {
t.test('lowerbound', function (st) {
st.plan(7)
var array = [2, 5, 8, 9, 45, 56, 78]
var lowerBound = util.findLowerBound(10, array)
let array = [2, 5, 8, 9, 45, 56, 78]
let lowerBound = util.findLowerBound(10, array)
st.equal(lowerBound, 3)
lowerBound = util.findLowerBound(3, array)
@ -33,14 +33,14 @@ tape('Util', function (t) {
tape('util.groupBy on valid input', function (t) {
t.plan(1)
var result = util.groupBy([
const result = util.groupBy([
{category: 'GAS', name: 'a'},
{category: 'SEC', name: 'b'},
{category: 'GAS', name: 'c'}
], 'category')
var expectedResult = {
const expectedResult = {
'GAS': [
{category: 'GAS', name: 'a'},
{category: 'GAS', name: 'c'}
@ -63,7 +63,7 @@ tape('util.concatWithSeperator valid output', function (t) {
tape('util.escapeRegExp', function (t) {
t.plan(3)
var original = 'function (uint256) returns (bool)'
const original = 'function (uint256) returns (bool)'
t.equal(util.escapeRegExp('abcd'), 'abcd', 'String with no regex')
t.equal(util.escapeRegExp(original), 'function \\(uint256\\) returns \\(bool\\)', 'function string with regex')
t.ok(new RegExp(util.escapeRegExp(original)).test(original), 'should still test for original string')
@ -71,9 +71,9 @@ tape('util.escapeRegExp', function (t) {
tape('util.compareByteCode', function (t) {
t.plan(1)
var address = 'c2a9cef5420203c2672f0e4325cca774893cca98'
var nullAddress = '0000000000000000000000000000000000000000'
var deployedLibraryByteCode = '0x73c2a9cef5420203c2672f0e4325cca774893cca983014608060405260043610610058576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063f26ea02c1461005d575b600080fd5b81801561006957600080fd5b506100886004803603810190808035906020019092919050505061008a565b005b600081600101600060648110151561009e57fe5b600502016002018190555060008160010160006064811015156100bd57fe5b600502016004018190555060008160010160006064811015156100dc57fe5b6005020160030181905550600081600001819055506001816101f501819055816101f601819055506064816101f70181905550505600a165627a7a723058203a6f106db7413fd9cad962bc12ba2327799d6b1334335f7bb854eab04200b3bf0029'
const address = 'c2a9cef5420203c2672f0e4325cca774893cca98'
const nullAddress = '0000000000000000000000000000000000000000'
const deployedLibraryByteCode = '0x73c2a9cef5420203c2672f0e4325cca774893cca983014608060405260043610610058576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063f26ea02c1461005d575b600080fd5b81801561006957600080fd5b506100886004803603810190808035906020019092919050505061008a565b005b600081600101600060648110151561009e57fe5b600502016002018190555060008160010160006064811015156100bd57fe5b600502016004018190555060008160010160006064811015156100dc57fe5b6005020160030181905550600081600001819055506001816101f501819055816101f601819055506064816101f70181905550505600a165627a7a723058203a6f106db7413fd9cad962bc12ba2327799d6b1334335f7bb854eab04200b3bf0029'
t.ok(util.compareByteCode(deployedLibraryByteCode, deployedLibraryByteCode.replace(address, nullAddress)), 'library bytecode should be the same')
})

@ -1,5 +1,5 @@
var Compiler = require('./src/compiler/compiler')
var CompilerInput = require('./src/compiler/compiler-input')
const Compiler = require('./src/compiler/compiler')
const CompilerInput = require('./src/compiler/compiler-input')
module.exports = {
Compiler: Compiler,

File diff suppressed because it is too large Load Diff

@ -14,6 +14,7 @@
],
"main": "./index.js",
"dependencies": {
"eslint-scope": "^5.0.0",
"remix-lib": "0.4.18",
"solc": "^0.6.0",
"webworkify": "^1.2.1"

@ -1,13 +1,13 @@
'use strict'
var solc = require('solc/wrapper')
const solc = require('solc/wrapper')
var compileJSON = function () { return '' }
var missingInputs = []
let compileJSON = function () { return '' }
const missingInputs = []
module.exports = function (self) {
self.addEventListener('message', function (e) {
var data = e.data
self.addEventListener('message', (e) => {
const data = e.data
switch (data.cmd) {
case 'loadVersion':
delete self.Module
@ -18,7 +18,7 @@ module.exports = function (self) {
self.importScripts(data.data)
var compiler = solc(self.Module)
const compiler = solc(self.Module)
compileJSON = function (input) {
try {

@ -1,16 +1,16 @@
'use strict'
var solc = require('solc/wrapper')
var solcABI = require('solc/abi')
const solc = require('solc/wrapper')
const solcABI = require('solc/abi')
var webworkify = require('webworkify')
const webworkify = require('webworkify')
var compilerInput = require('./compiler-input')
const compilerInput = require('./compiler-input')
var remixLib = require('remix-lib')
var EventManager = remixLib.EventManager
const remixLib = require('remix-lib')
const EventManager = remixLib.EventManager
var txHelper = require('./txHelper')
const txHelper = require('./txHelper')
/*
trigger compilationFinished, compilerLoaded, compilationStarted, compilationDuration
@ -19,17 +19,17 @@ function Compiler (handleImportCall) {
var self = this
this.event = new EventManager()
var compileJSON
let compileJSON
var worker = null
let worker = null
var currentVersion
let currentVersion
var optimize = false
let optimize = false
var evmVersion = null
let evmVersion = null
var language = 'Solidity'
let language = 'Solidity'
this.setOptimize = function (_optimize) {
optimize = _optimize
@ -43,7 +43,7 @@ function Compiler (handleImportCall) {
language = _language
}
var compilationStartTime = null
let compilationStartTime = null
this.event.register('compilationFinished', (success, data, source) => {
if (success && compilationStartTime) {
this.event.trigger('compilationDuration', [(new Date().getTime()) - compilationStartTime])
@ -55,18 +55,18 @@ function Compiler (handleImportCall) {
compilationStartTime = new Date().getTime()
})
var internalCompile = function (files, target, missingInputs) {
gatherImports(files, target, missingInputs, function (error, input) {
const internalCompile = (files, target, missingInputs) => {
gatherImports(files, target, missingInputs, (error, input) => {
if (error) {
self.lastCompilationResult = null
self.event.trigger('compilationFinished', [false, {'error': { formattedMessage: error, severity: 'error' }}, files])
this.lastCompilationResult = null
this.event.trigger('compilationFinished', [false, {'error': { formattedMessage: error, severity: 'error' }}, files])
} else {
compileJSON(input)
}
})
}
var compile = function (files, target) {
const compile = function (files, target) {
self.event.trigger('compilationStarted', [])
internalCompile(files, target)
}
@ -84,7 +84,7 @@ function Compiler (handleImportCall) {
function onInternalCompilerLoaded () {
if (worker === null) {
var compiler
let compiler
if (typeof (window) === 'undefined') {
compiler = require('solc')
} else {
@ -92,15 +92,15 @@ function Compiler (handleImportCall) {
}
compileJSON = function (source) {
var missingInputs = []
var missingInputsCallback = function (path) {
const missingInputs = []
const missingInputsCallback = function (path) {
missingInputs.push(path)
return { error: 'Deferred import' }
}
var result
let result
try {
var input = compilerInput(source.sources, {optimize: optimize, evmVersion: evmVersion, language: language, target: source.target})
const input = compilerInput(source.sources, {optimize: optimize, evmVersion: evmVersion, language: language, target: source.target})
result = compiler.compile(input, { import: missingInputsCallback })
result = JSON.parse(result)
} catch (exception) {
@ -189,7 +189,7 @@ function Compiler (handleImportCall) {
}
function compilationFinished (data, missingInputs, source) {
var noFatalErrors = true // ie warnings are ok
let noFatalErrors = true // ie warnings are ok
function isValidError (error) {
// The deferred import is not a real error
@ -236,9 +236,9 @@ function Compiler (handleImportCall) {
}
// TODO: needs to be changed to be more node friendly
this.loadVersion = function (usingWorker, url) {
this.loadVersion = (usingWorker, url) => {
console.log('Loading ' + url + ' ' + (usingWorker ? 'with worker' : 'without worker'))
self.event.trigger('loadingCompiler', [url, usingWorker])
this.event.trigger('loadingCompiler', [url, usingWorker])
if (worker !== null) {
worker.terminate()
@ -261,11 +261,11 @@ function Compiler (handleImportCall) {
compilationFinished({ error: { formattedMessage: 'Compiler not yet loaded.' } })
})
var newScript = document.createElement('script')
const newScript = document.createElement('script')
newScript.type = 'text/javascript'
newScript.src = url
document.getElementsByTagName('head')[0].appendChild(newScript)
var check = window.setInterval(function () {
const check = window.setInterval(function () {
if (!window.Module) {
return
}
@ -276,21 +276,21 @@ function Compiler (handleImportCall) {
function loadWorker (url) {
worker = webworkify(require('./compiler-worker.js'))
var jobs = []
const jobs = []
worker.addEventListener('message', function (msg) {
var data = msg.data
const data = msg.data
switch (data.cmd) {
case 'versionLoaded':
onCompilerLoaded(data.data)
break
case 'compiled':
var result
let result
try {
result = JSON.parse(data.data)
} catch (exception) {
result = { 'error': 'Invalid JSON output from the compiler: ' + exception }
}
var sources = {}
let sources = {}
if (data.job in jobs !== undefined) {
sources = jobs[data.job].sources
delete jobs[data.job]
@ -316,14 +316,14 @@ function Compiler (handleImportCall) {
// FIXME: This will only match imports if the file begins with one.
// It should tokenize by lines and check each.
// eslint-disable-next-line no-useless-escape
var importRegex = /^\s*import\s*[\'\"]([^\'\"]+)[\'\"];/g
let importRegex = /^\s*import\s*[\'\"]([^\'\"]+)[\'\"];/g
for (var fileName in files) {
var match
let match
while ((match = importRegex.exec(files[fileName].content))) {
var importFilePath = match[1]
let importFilePath = match[1]
if (importFilePath.startsWith('./')) {
var path = /(.*\/).*/.exec(fileName)
const path = /(.*\/).*/.exec(fileName)
if (path !== null) {
importFilePath = importFilePath.replace('./', path[1])
} else {
@ -339,7 +339,7 @@ function Compiler (handleImportCall) {
}
while (importHints.length > 0) {
var m = importHints.pop()
let m = importHints.pop()
if (m in files) {
continue
}
@ -362,13 +362,13 @@ function Compiler (handleImportCall) {
}
function truncateVersion (version) {
var tmp = /^(\d+.\d+.\d+)/.exec(version)
const tmp = /^(\d+.\d+.\d+)/.exec(version)
if (tmp) {
return tmp[1]
}
return version
}
function updateInterface (data) {
txHelper.visitContracts(data.contracts, (contract) => {
if (!contract.object.abi) contract.object.abi = []

@ -9,7 +9,7 @@ module.exports = {
* @returns contract obj and associated file: { contract, file } or null
*/
getContract: (contractName, contracts) => {
for (var file in contracts) {
for (let file in contracts) {
if (contracts[file][contractName]) {
return { object: contracts[file][contractName], file: file }
}
@ -23,8 +23,8 @@ module.exports = {
* @param {Function} cb - callback
*/
visitContracts: (contracts, cb) => {
for (var file in contracts) {
for (var name in contracts[file]) {
for (let file in contracts) {
for (let name in contracts[file]) {
if (cb({ name: name, object: contracts[file][name], file: file })) return
}
}

Loading…
Cancel
Save