update remix-lib syntax to use const, let and this

pull/5370/head
Iuri Matias 5 years ago
parent 1bbc257f72
commit 51fd3ddf14
  1. 52
      remix-lib/index.js
  2. 8
      remix-lib/src/astWalker.js
  3. 28
      remix-lib/src/code/breakpointManager.js
  4. 40
      remix-lib/src/code/codeManager.js
  5. 21
      remix-lib/src/code/codeResolver.js
  6. 30
      remix-lib/src/code/codeUtils.js
  7. 26
      remix-lib/src/code/disassembler.js
  8. 6
      remix-lib/src/code/opcodes.js
  9. 6
      remix-lib/src/eventManager.js
  10. 32
      remix-lib/src/execution/eventsDecoder.js
  11. 87
      remix-lib/src/execution/execution-context.js
  12. 2
      remix-lib/src/execution/txExecution.js
  13. 104
      remix-lib/src/execution/txFormat.js
  14. 37
      remix-lib/src/execution/txHelper.js
  15. 69
      remix-lib/src/execution/txListener.js
  16. 50
      remix-lib/src/execution/txRunner.js
  17. 10
      remix-lib/src/execution/typeConversion.js
  18. 9
      remix-lib/src/helpers/traceHelper.js
  19. 24
      remix-lib/src/helpers/uiHelper.js
  20. 8
      remix-lib/src/init.js
  21. 8
      remix-lib/src/offsetToLineColumnConverter.js
  22. 32
      remix-lib/src/sourceLocationTracker.js
  23. 50
      remix-lib/src/sourceMappingDecoder.js
  24. 2
      remix-lib/src/storage.js
  25. 36
      remix-lib/src/trace/traceAnalyser.js
  26. 18
      remix-lib/src/trace/traceCache.js
  27. 58
      remix-lib/src/trace/traceManager.js
  28. 2
      remix-lib/src/trace/traceRetriever.js
  29. 18
      remix-lib/src/trace/traceStepManager.js
  30. 62
      remix-lib/src/util.js
  31. 13
      remix-lib/src/web3Provider/dummyProvider.js
  32. 8
      remix-lib/src/web3Provider/web3Providers.js
  33. 99
      remix-lib/src/web3Provider/web3VmProvider.js
  34. 10
      remix-lib/test/astwalker.js
  35. 24
      remix-lib/test/codeManager.js
  36. 8
      remix-lib/test/disassembler.js
  37. 12
      remix-lib/test/eventManager.js
  38. 2
      remix-lib/test/init.js
  39. 2
      remix-lib/test/resources/ast.js
  40. 2
      remix-lib/test/resources/sourceMapping.js
  41. 6
      remix-lib/test/resources/testWeb3.js
  42. 34
      remix-lib/test/sourceMappingDecoder.js
  43. 22
      remix-lib/test/traceManager.js
  44. 120
      remix-lib/test/txFormat.js
  45. 8
      remix-lib/test/txHelper.js
  46. 20
      remix-lib/test/util.js

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

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

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

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

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

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

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

@ -1,5 +1,5 @@
'use strict' 'use strict'
var codes = { const codes = {
// 0x0 range - arithmetic ops // 0x0 range - arithmetic ops
// name, baseCost, off stack, on stack, dynamic, async // 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 // @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) { module.exports = function (op, full) {
var code = codes[op] ? codes[op] : ['INVALID', 0, 0, 0, false, false] const code = codes[op] ? codes[op] : ['INVALID', 0, 0, 0, false, false]
var opcode = code[0] let opcode = code[0]
if (full) { if (full) {
if (opcode === 'LOG') { if (opcode === 'LOG') {

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

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

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

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

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

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

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

@ -1,10 +1,10 @@
'use strict' 'use strict'
var EthJSTX = require('ethereumjs-tx').Transaction const EthJSTX = require('ethereumjs-tx').Transaction
var EthJSBlock = require('ethereumjs-block') const EthJSBlock = require('ethereumjs-block')
var ethJSUtil = require('ethereumjs-util') const ethJSUtil = require('ethereumjs-util')
var BN = ethJSUtil.BN const BN = ethJSUtil.BN
var defaultExecutionContext = require('./execution-context') const defaultExecutionContext = require('./execution-context')
var EventManager = require('../eventManager') const EventManager = require('../eventManager')
class TxRunner { class TxRunner {
constructor (vmaccounts, api, executionContext) { constructor (vmaccounts, api, executionContext) {
@ -26,7 +26,7 @@ class TxRunner {
} }
rawRun (args, confirmationCb, gasEstimationForceSend, promptCb, cb) { rawRun (args, confirmationCb, gasEstimationForceSend, promptCb, cb) {
var timestamp = Date.now() let timestamp = Date.now()
if (args.timestamp) { if (args.timestamp) {
timestamp = args.timestamp timestamp = args.timestamp
} }
@ -50,15 +50,14 @@ class TxRunner {
} }
_sendTransaction (sendTx, tx, pass, callback) { _sendTransaction (sendTx, tx, pass, callback) {
var self = this const cb = (err, resp) => {
var cb = function (err, resp) {
if (err) { if (err) {
return callback(err, resp) return callback(err, resp)
} }
self.event.trigger('transactionBroadcasted', [resp]) this.event.trigger('transactionBroadcasted', [resp])
var listenOnResponse = () => { var listenOnResponse = () => {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
var result = await tryTillReceiptAvailable(resp) const result = await tryTillReceiptAvailable(resp)
tx = await tryTillTxAvailable(resp) tx = await tryTillTxAvailable(resp)
resolve({ resolve({
result, result,
@ -69,7 +68,7 @@ class TxRunner {
} }
listenOnResponse().then((txData) => { callback(null, txData) }).catch((error) => { callback(error) }) 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 { try {
sendTx.apply({}, args) sendTx.apply({}, args)
} catch (e) { } catch (e) {
@ -78,18 +77,16 @@ class TxRunner {
} }
execute (args, confirmationCb, gasEstimationForceSend, promptCb, callback) { execute (args, confirmationCb, gasEstimationForceSend, promptCb, callback) {
var self = this let data = args.data
var data = args.data
if (data.slice(0, 2) !== '0x') { if (data.slice(0, 2) !== '0x') {
data = '0x' + data data = '0x' + data
} }
if (!this.executionContext.isVM()) { 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 { } else {
try { 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) { } catch (e) {
callback(e, null) callback(e, null)
} }
@ -165,8 +162,7 @@ class TxRunner {
} }
runInNode (from, to, data, value, gasLimit, useCall, confirmCb, gasEstimationForceSend, promptCb, callback) { runInNode (from, to, data, value, gasLimit, useCall, confirmCb, gasEstimationForceSend, promptCb, callback) {
const self = this const tx = { from: from, to: to, data: data, value: value }
var tx = { from: from, to: to, data: data, value: value }
if (useCall) { if (useCall) {
tx.gas = gasLimit 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, () => { gasEstimationForceSend(err, () => {
// callback is called whenever no error // callback is called whenever no error
tx.gas = !gasEstimation ? gasLimit : gasEstimation tx.gas = !gasEstimation ? gasLimit : gasEstimation
if (self._api.config.getUnpersistedProperty('doNotShowTransactionConfirmationAgain')) { if (this._api.config.getUnpersistedProperty('doNotShowTransactionConfirmationAgain')) {
return self._executeTx(tx, null, self._api, promptCb, callback) return this._executeTx(tx, null, this._api, promptCb, callback)
} }
self._api.detectNetwork((err, network) => { this._api.detectNetwork((err, network) => {
if (err) { if (err) {
console.log(err) console.log(err)
return return
} }
confirmCb(network, tx, tx.gas, (gasPrice) => { 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) => { }, (error) => {
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 // 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 // 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) 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 warnEstimation += ' ' + err
if (gasEstimation > gasLimit) { if (gasEstimation > gasLimit) {
@ -257,7 +253,7 @@ function run (self, tx, stamp, confirmationCb, gasEstimationForceSend, promptCb,
delete self.pendingTxs[stamp] delete self.pendingTxs[stamp]
callback(error, result) callback(error, result)
if (self.queusTxs.length) { if (self.queusTxs.length) {
var next = self.queusTxs.pop() const next = self.queusTxs.pop()
run(self, next.tx, next.stamp, next.callback) run(self, next.tx, next.stamp, next.callback)
} }
}) })

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

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

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

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

@ -1,12 +1,12 @@
'use strict' 'use strict'
var SourceMappingDecoder = require('./sourceMappingDecoder') const SourceMappingDecoder = require('./sourceMappingDecoder')
function offsetToColumnConverter (compilerEvent) { function offsetToColumnConverter (compilerEvent) {
this.lineBreakPositionsByContent = {} this.lineBreakPositionsByContent = {}
this.sourceMappingDecoder = new SourceMappingDecoder() this.sourceMappingDecoder = new SourceMappingDecoder()
var self = this var self = this
if (compilerEvent) { if (compilerEvent) {
compilerEvent.register('compilationFinished', function (success, data, source) { compilerEvent.register('compilationFinished', (success, data, source) => {
self.clear() self.clear()
}) })
} }
@ -14,8 +14,8 @@ function offsetToColumnConverter (compilerEvent) {
offsetToColumnConverter.prototype.offsetToLineColumn = function (rawLocation, file, sources, asts) { offsetToColumnConverter.prototype.offsetToLineColumn = function (rawLocation, file, sources, asts) {
if (!this.lineBreakPositionsByContent[file]) { if (!this.lineBreakPositionsByContent[file]) {
for (var filename in asts) { for (let filename in asts) {
var source = asts[filename] 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 // 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 (typeof source.id === 'string') source.id = parseInt(source.id, 10)
if (source.id === file) { if (source.id === file) {

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

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

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

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

@ -1,5 +1,5 @@
'use strict' 'use strict'
var helper = require('../util') const helper = require('../util')
function TraceCache () { function TraceCache () {
this.init() this.init()
@ -38,7 +38,7 @@ TraceCache.prototype.pushMemoryChanges = function (value) {
// outOfGas has been removed because gas left logging is apparently made differently // 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) // 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) { 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 (validReturnStep || reverted) {
if (this.currentCall) { if (this.currentCall) {
this.currentCall.call.return = index - 1 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 this.currentCall = parent ? { call: parent.call, parent: parent.parent } : null
} }
} else { } else {
var call = { let call = {
op: step.op, op: step.op,
address: address, address: address,
callStack: callStack, callStack: callStack,
@ -71,10 +71,10 @@ TraceCache.prototype.pushReturnValue = function (step, value) {
} }
TraceCache.prototype.pushContractCreationFromMemory = function (index, token, trace, lastMemoryChange) { TraceCache.prototype.pushContractCreationFromMemory = function (index, token, trace, lastMemoryChange) {
var memory = trace[lastMemoryChange].memory const memory = trace[lastMemoryChange].memory
var stack = trace[index].stack const stack = trace[index].stack
var offset = 2 * parseInt(stack[stack.length - 2], 16) const offset = 2 * parseInt(stack[stack.length - 2], 16)
var size = 2 * parseInt(stack[stack.length - 3], 16) const size = 2 * parseInt(stack[stack.length - 3], 16)
this.contractCreation[token] = '0x' + memory.join('').substr(offset, size) 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) { TraceCache.prototype.accumulateStorageChanges = function (index, address, storage) {
var ret = Object.assign({}, storage) const ret = Object.assign({}, storage)
for (var k in this.storageChanges) { for (var k in this.storageChanges) {
var changesIndex = this.storageChanges[k] const changesIndex = this.storageChanges[k]
if (changesIndex > index) { if (changesIndex > index) {
return ret return ret
} }

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

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

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

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

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

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

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

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

@ -1,28 +1,28 @@
'use strict' 'use strict'
var tape = require('tape') const tape = require('tape')
var Web3Providers = require('../src/web3Provider/web3Providers') const Web3Providers = require('../src/web3Provider/web3Providers')
var TraceManager = require('../src/trace/traceManager') const TraceManager = require('../src/trace/traceManager')
var CodeManager = require('../src/code/codeManager') const CodeManager = require('../src/code/codeManager')
var web3Test = require('./resources/testWeb3') const web3Test = require('./resources/testWeb3')
let web3 = null let web3 = null
tape('CodeManager', function (t) { tape('CodeManager', function (t) {
var codeManager let codeManager
var web3Providers = new Web3Providers() const web3Providers = new Web3Providers()
web3Providers.addProvider('TEST', web3Test) web3Providers.addProvider('TEST', web3Test)
web3Providers.get('TEST', function (error, obj) { web3Providers.get('TEST', function (error, obj) {
if (error) { if (error) {
var mes = 'provider TEST not defined' const mes = 'provider TEST not defined'
console.log(mes) console.log(mes)
t.fail(mes) t.fail(mes)
} else { } else {
web3 = obj web3 = obj
var traceManager = new TraceManager({web3: web3}) const traceManager = new TraceManager({web3: web3})
codeManager = new CodeManager(traceManager) 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 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) { traceManager.resolveTrace(tx, function (error, result) {
if (error) { if (error) {
t.fail(' - traceManager.resolveTrace - failed ' + result) 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(0, tx)
codeManager.resolveStep(70, tx) codeManager.resolveStep(70, tx)
}) })

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

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

@ -9,7 +9,7 @@ var init = {
}, },
readFile: function (filename, callback) { readFile: function (filename, callback) {
var fs = require('fs') const fs = require('fs')
try { try {
console.log('reading ' + filename) console.log('reading ' + filename)
if (callback) { 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"}} 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.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 { sourceRuntimeMapping.source = `contract test {
int x; int x;

@ -1,9 +1,9 @@
'use strict' 'use strict'
var init = require('../init') const init = require('../init')
var web3Override = {} const web3Override = {}
web3Override.eth = {} web3Override.eth = {}
web3Override.debug = {} 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) data = JSON.parse(data)
web3Override.eth.getCode = function (address, callback) { web3Override.eth.getCode = function (address, callback) {

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

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

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

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

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

Loading…
Cancel
Save