From 51fd3ddf14b2a2730db194063a83734ec876d5c0 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Sun, 22 Dec 2019 14:55:31 -0500 Subject: [PATCH] update remix-lib syntax to use const, let and this --- remix-lib/index.js | 52 ++++---- remix-lib/src/astWalker.js | 8 +- remix-lib/src/code/breakpointManager.js | 28 ++--- remix-lib/src/code/codeManager.js | 40 +++---- remix-lib/src/code/codeResolver.js | 21 ++-- remix-lib/src/code/codeUtils.js | 30 ++--- remix-lib/src/code/disassembler.js | 26 ++-- remix-lib/src/code/opcodes.js | 6 +- remix-lib/src/eventManager.js | 6 +- remix-lib/src/execution/eventsDecoder.js | 32 ++--- remix-lib/src/execution/execution-context.js | 87 +++++++------- remix-lib/src/execution/txExecution.js | 2 +- remix-lib/src/execution/txFormat.js | 104 ++++++++-------- remix-lib/src/execution/txHelper.js | 37 +++--- remix-lib/src/execution/txListener.js | 69 +++++------ remix-lib/src/execution/txRunner.js | 50 ++++---- remix-lib/src/execution/typeConversion.js | 10 +- remix-lib/src/helpers/traceHelper.js | 9 +- remix-lib/src/helpers/uiHelper.js | 24 ++-- remix-lib/src/init.js | 8 +- remix-lib/src/offsetToLineColumnConverter.js | 8 +- remix-lib/src/sourceLocationTracker.js | 32 +++-- remix-lib/src/sourceMappingDecoder.js | 50 ++++---- remix-lib/src/storage.js | 2 +- remix-lib/src/trace/traceAnalyser.js | 36 +++--- remix-lib/src/trace/traceCache.js | 18 +-- remix-lib/src/trace/traceManager.js | 58 ++++----- remix-lib/src/trace/traceRetriever.js | 2 +- remix-lib/src/trace/traceStepManager.js | 18 +-- remix-lib/src/util.js | 62 +++++----- remix-lib/src/web3Provider/dummyProvider.js | 13 +- remix-lib/src/web3Provider/web3Providers.js | 8 +- remix-lib/src/web3Provider/web3VmProvider.js | 99 ++++++++------- remix-lib/test/astwalker.js | 10 +- remix-lib/test/codeManager.js | 24 ++-- remix-lib/test/disassembler.js | 8 +- remix-lib/test/eventManager.js | 12 +- remix-lib/test/init.js | 2 +- remix-lib/test/resources/ast.js | 2 +- remix-lib/test/resources/sourceMapping.js | 2 +- remix-lib/test/resources/testWeb3.js | 6 +- remix-lib/test/sourceMappingDecoder.js | 34 +++--- remix-lib/test/traceManager.js | 22 ++-- remix-lib/test/txFormat.js | 120 +++++++++---------- remix-lib/test/txHelper.js | 8 +- remix-lib/test/util.js | 20 ++-- 46 files changed, 658 insertions(+), 667 deletions(-) diff --git a/remix-lib/index.js b/remix-lib/index.js index d1ba71cb16..b60cbfdb7b 100644 --- a/remix-lib/index.js +++ b/remix-lib/index.js @@ -1,33 +1,33 @@ 'use strict' -var EventManager = require('./src/eventManager') -var traceHelper = require('./src/helpers/traceHelper') -var uiHelper = require('./src/helpers/uiHelper') -var compilerHelper = require('./src/helpers/compilerHelper') -var SourceMappingDecoder = require('./src/sourceMappingDecoder') -var SourceLocationTracker = require('./src/sourceLocationTracker') -var OffsetToColumnConverter = require('./src/offsetToLineColumnConverter') -var init = require('./src/init') -var util = require('./src/util') -var Web3Providers = require('./src/web3Provider/web3Providers') -var DummyProvider = require('./src/web3Provider/dummyProvider') -var Web3VMProvider = require('./src/web3Provider/web3VmProvider') -var AstWalker = require('./src/astWalker') -var Storage = require('./src/storage') +const EventManager = require('./src/eventManager') +const traceHelper = require('./src/helpers/traceHelper') +const uiHelper = require('./src/helpers/uiHelper') +const compilerHelper = require('./src/helpers/compilerHelper') +const SourceMappingDecoder = require('./src/sourceMappingDecoder') +const SourceLocationTracker = require('./src/sourceLocationTracker') +const OffsetToColumnConverter = require('./src/offsetToLineColumnConverter') +const init = require('./src/init') +const util = require('./src/util') +const Web3Providers = require('./src/web3Provider/web3Providers') +const DummyProvider = require('./src/web3Provider/dummyProvider') +const Web3VMProvider = require('./src/web3Provider/web3VmProvider') +const AstWalker = require('./src/astWalker') +const Storage = require('./src/storage') -var EventsDecoder = require('./src/execution/eventsDecoder') -var txExecution = require('./src/execution/txExecution') -var txHelper = require('./src/execution/txHelper') -var txFormat = require('./src/execution/txFormat') -var txListener = require('./src/execution/txListener') -var txRunner = require('./src/execution/txRunner') -var executionContext = require('./src/execution/execution-context') -var typeConversion = require('./src/execution/typeConversion') +const EventsDecoder = require('./src/execution/eventsDecoder') +const txExecution = require('./src/execution/txExecution') +const txHelper = require('./src/execution/txHelper') +const txFormat = require('./src/execution/txFormat') +const txListener = require('./src/execution/txListener') +const txRunner = require('./src/execution/txRunner') +const executionContext = require('./src/execution/execution-context') +const typeConversion = require('./src/execution/typeConversion') -var CodeManager = require('./src/code/codeManager') -var BreakpointManager = require('./src/code/breakpointManager') -var TraceManager = require('./src/trace/traceManager') +const CodeManager = require('./src/code/codeManager') +const BreakpointManager = require('./src/code/breakpointManager') +const TraceManager = require('./src/trace/traceManager') -var UniversalDApp = require('./src/universalDapp') +const UniversalDApp = require('./src/universalDapp') if (typeof (module) !== 'undefined' && typeof (module.exports) !== 'undefined') { module.exports = modules() diff --git a/remix-lib/src/astWalker.js b/remix-lib/src/astWalker.js index 92ce33227c..5768b3ab98 100644 --- a/remix-lib/src/astWalker.js +++ b/remix-lib/src/astWalker.js @@ -23,8 +23,8 @@ AstWalker.prototype.walk = function (ast, callback) { callback['*'] = function () { return true } } if (manageCallBack(ast, callback) && ast.children && ast.children.length > 0) { - for (var k in ast.children) { - var child = ast.children[k] + for (let k in ast.children) { + const child = ast.children[k] this.walk(child, callback) } } @@ -37,8 +37,8 @@ AstWalker.prototype.walk = function (ast, callback) { * @param {Function} - callback used by AstWalker to compute response */ AstWalker.prototype.walkAstList = function (sourcesList, callback) { - var walker = new AstWalker() - for (var k in sourcesList) { + const walker = new AstWalker() + for (let k in sourcesList) { walker.walk(sourcesList[k].legacyAST, callback) } } diff --git a/remix-lib/src/code/breakpointManager.js b/remix-lib/src/code/breakpointManager.js index a9ef73d7ab..b45232f122 100644 --- a/remix-lib/src/code/breakpointManager.js +++ b/remix-lib/src/code/breakpointManager.js @@ -1,7 +1,7 @@ 'use strict' -var EventManager = require('../eventManager') -var helper = require('../helpers/traceHelper') +const EventManager = require('../eventManager') +const helper = require('../helpers/traceHelper') /** * allow to manage breakpoint @@ -74,10 +74,10 @@ class BreakpointManager { } } - var sourceLocation - var previousSourceLocation - var currentStep = fromStep + direction - var lineHadBreakpoint = false + let sourceLocation + let previousSourceLocation + let currentStep = fromStep + direction + let lineHadBreakpoint = false while (currentStep > 0 && currentStep < this.debugger.traceManager.trace.length) { try { previousSourceLocation = sourceLocation @@ -86,7 +86,7 @@ class BreakpointManager { console.log('cannot jump to breakpoint ' + e) return } - var lineColumn = this.locationToRowConverter(sourceLocation) + let lineColumn = this.locationToRowConverter(sourceLocation) if (this.previousLine !== lineColumn.start.line) { if (direction === -1 && lineHadBreakpoint) { // TODO : improve this when we will build the correct structure before hand lineHadBreakpoint = false @@ -124,11 +124,11 @@ class BreakpointManager { * @return {Bool} return true if the given @arg fileIndex @arg line refers to a breakpoint */ hasBreakpointAtLine (fileIndex, line) { - var filename = this.debugger.solidityProxy.fileNameFromIndex(fileIndex) + const filename = this.debugger.solidityProxy.fileNameFromIndex(fileIndex) if (filename && this.breakpoints[filename]) { - var sources = this.breakpoints[filename] - for (var k in sources) { - var source = sources[k] + const sources = this.breakpoints[filename] + for (let k in sources) { + const source = sources[k] if (line === source.row) { return true } @@ -143,7 +143,7 @@ class BreakpointManager { * @return {Bool} true if breapoint registered */ hasBreakpoint () { - for (var k in this.breakpoints) { + for (let k in this.breakpoints) { if (this.breakpoints[k].length) { return true } @@ -172,8 +172,8 @@ class BreakpointManager { remove (sourceLocation) { if (this.breakpoints[sourceLocation.fileName]) { var sources = this.breakpoints[sourceLocation.fileName] - for (var k in sources) { - var source = sources[k] + for (let k in sources) { + const source = sources[k] if (sourceLocation.row === source.row) { sources.splice(k, 1) this.event.trigger('breakpointRemoved', [sourceLocation]) diff --git a/remix-lib/src/code/codeManager.js b/remix-lib/src/code/codeManager.js index 0664a0e353..9aaea9b4d6 100644 --- a/remix-lib/src/code/codeManager.js +++ b/remix-lib/src/code/codeManager.js @@ -1,9 +1,9 @@ 'use strict' -var EventManager = require('../eventManager') -var traceHelper = require('../helpers/traceHelper') -var SourceMappingDecoder = require('../sourceMappingDecoder') -var CodeResolver = require('./codeResolver') +const EventManager = require('../eventManager') +const traceHelper = require('../helpers/traceHelper') +const SourceMappingDecoder = require('../sourceMappingDecoder') +const CodeResolver = require('./codeResolver') /* resolve contract code referenced by vmtrace in order to be used by asm listview. @@ -36,15 +36,14 @@ CodeManager.prototype.clear = function () { CodeManager.prototype.resolveStep = function (stepIndex, tx) { if (stepIndex < 0) return this.event.trigger('resolvingStep') - var self = this if (stepIndex === 0) { - retrieveCodeAndTrigger(self, tx.to, stepIndex, tx) + retrieveCodeAndTrigger(this, tx.to, stepIndex, tx) } else { - this.traceManager.getCurrentCalledAddressAt(stepIndex, function (error, address) { + this.traceManager.getCurrentCalledAddressAt(stepIndex, (error, address) => { if (error) { console.log(error) } else { - retrieveCodeAndTrigger(self, address, stepIndex, tx) + retrieveCodeAndTrigger(this, address, stepIndex, tx) } }) } @@ -57,13 +56,12 @@ CodeManager.prototype.resolveStep = function (stepIndex, tx) { * @param {Function} cb - callback function, return the bytecode */ CodeManager.prototype.getCode = function (address, cb) { - const self = this if (traceHelper.isContractCreation(address)) { var codes = this.codeResolver.getExecutingCodeFromCache(address) if (!codes) { - this.traceManager.getContractCreationCode(address, function (error, hexCode) { + this.traceManager.getContractCreationCode(address, (error, hexCode) => { if (!error) { - codes = self.codeResolver.cacheExecutingCode(address, hexCode) + codes = this.codeResolver.cacheExecutingCode(address, hexCode) cb(null, codes) } }) @@ -71,7 +69,7 @@ CodeManager.prototype.getCode = function (address, cb) { cb(null, codes) } } else { - this.codeResolver.resolveCode(address, function (address, code) { + this.codeResolver.resolveCode(address, (address, code) => { cb(null, code) }) } @@ -86,18 +84,17 @@ CodeManager.prototype.getCode = function (address, cb) { * @return {Object} return the ast node of the function */ CodeManager.prototype.getFunctionFromStep = function (stepIndex, sourceMap, ast) { - var self = this - this.traceManager.getCurrentCalledAddressAt(stepIndex, function (error, address) { + this.traceManager.getCurrentCalledAddressAt(stepIndex, (error, address) => { if (error) { console.log(error) return { error: 'Cannot retrieve current address for ' + stepIndex } } else { - self.traceManager.getCurrentPC(stepIndex, function (error, pc) { + this.traceManager.getCurrentPC(stepIndex, (error, pc) => { if (error) { console.log(error) return { error: 'Cannot retrieve current PC for ' + stepIndex } } else { - return self.getFunctionFromPC(address, pc, sourceMap, ast) + return this.getFunctionFromPC(address, pc, sourceMap, ast) } }) } @@ -112,13 +109,12 @@ CodeManager.prototype.getFunctionFromStep = function (stepIndex, sourceMap, ast) * @param {Function} callback - instruction index */ CodeManager.prototype.getInstructionIndex = function (address, step, callback) { - const self = this - this.traceManager.getCurrentPC(step, function (error, pc) { + this.traceManager.getCurrentPC(step, (error, pc) => { if (error) { console.log(error) callback('Cannot retrieve current PC for ' + step, null) } else { - var itemIndex = self.codeResolver.getInstructionIndex(address, pc) + const itemIndex = this.codeResolver.getInstructionIndex(address, pc) callback(null, itemIndex) } }) @@ -134,12 +130,12 @@ CodeManager.prototype.getInstructionIndex = function (address, step, callback) { * @return {Object} return the ast node of the function */ CodeManager.prototype.getFunctionFromPC = function (address, pc, sourceMap, ast) { - var instIndex = this.codeResolver.getInstructionIndex(address, pc) + const instIndex = this.codeResolver.getInstructionIndex(address, pc) return SourceMappingDecoder.findNodeAtInstructionIndex('FunctionDefinition', instIndex, sourceMap, ast) } function retrieveCodeAndTrigger (codeMananger, address, stepIndex, tx) { - codeMananger.getCode(address, function (error, result) { + codeMananger.getCode(address, (error, result) => { if (!error) { retrieveIndexAndTrigger(codeMananger, address, stepIndex, result.instructions) } else { @@ -149,7 +145,7 @@ function retrieveCodeAndTrigger (codeMananger, address, stepIndex, tx) { } function retrieveIndexAndTrigger (codeMananger, address, step, code) { - codeMananger.getInstructionIndex(address, step, function (error, result) { + codeMananger.getInstructionIndex(address, step, (error, result) => { if (!error) { codeMananger.event.trigger('changed', [code, address, result]) } else { diff --git a/remix-lib/src/code/codeResolver.js b/remix-lib/src/code/codeResolver.js index da52a74d3c..43ee055735 100644 --- a/remix-lib/src/code/codeResolver.js +++ b/remix-lib/src/code/codeResolver.js @@ -1,5 +1,5 @@ 'use strict' -var codeUtils = require('./codeUtils') +const codeUtils = require('./codeUtils') function CodeResolver (options) { this.web3 = options.web3 @@ -16,20 +16,18 @@ CodeResolver.prototype.clear = function () { } CodeResolver.prototype.resolveCode = function (address, callBack) { - var cache = this.getExecutingCodeFromCache(address) + const cache = this.getExecutingCodeFromCache(address) if (cache) { - callBack(address, cache) - return + return callBack(address, cache) } - var self = this - this.loadCode(address, function (code) { - callBack(address, self.cacheExecutingCode(address, code)) + this.loadCode(address, (code) => { + callBack(address, this.cacheExecutingCode(address, code)) }) } CodeResolver.prototype.loadCode = function (address, callback) { - this.web3.eth.getCode(address, function (error, result) { + this.web3.eth.getCode(address, (error, result) => { if (error) { console.log(error) } else { @@ -39,7 +37,7 @@ CodeResolver.prototype.loadCode = function (address, callback) { } CodeResolver.prototype.cacheExecutingCode = function (address, hexCode) { - var codes = this.formatCode(hexCode) + const codes = this.formatCode(hexCode) this.bytecodeByAddress[address] = hexCode this.instructionsByAddress[address] = codes.code this.instructionsIndexByBytesOffset[address] = codes.instructionsIndexByBytesOffset @@ -47,7 +45,7 @@ CodeResolver.prototype.cacheExecutingCode = function (address, hexCode) { } CodeResolver.prototype.formatCode = function (hexCode) { - var code = codeUtils.nameOpCodes(Buffer.from(hexCode.substring(2), 'hex')) + const code = codeUtils.nameOpCodes(Buffer.from(hexCode.substring(2), 'hex')) return { code: code[0], instructionsIndexByBytesOffset: code[1] @@ -61,9 +59,8 @@ CodeResolver.prototype.getExecutingCodeFromCache = function (address) { instructionsIndexByBytesOffset: this.instructionsIndexByBytesOffset[address], bytecode: this.bytecodeByAddress[address] } - } else { - return null } + return null } CodeResolver.prototype.getInstructionIndex = function (address, pc) { diff --git a/remix-lib/src/code/codeUtils.js b/remix-lib/src/code/codeUtils.js index 6105119d27..d522925e25 100644 --- a/remix-lib/src/code/codeUtils.js +++ b/remix-lib/src/code/codeUtils.js @@ -1,24 +1,24 @@ 'use strict' -var opcodes = require('./opcodes') +const opcodes = require('./opcodes') module.exports = { nameOpCodes: function (raw) { - var pushData = '' - var codeMap = {} - var code = [] + let pushData = '' + const codeMap = {} + const code = [] - for (var i = 0; i < raw.length; i++) { - var pc = i - var curOpCode = opcodes(raw[pc], false).name + for (let i = 0; i < raw.length; i++) { + const pc = i + const curOpCode = opcodes(raw[pc], false).name codeMap[i] = code.length // no destinations into the middle of PUSH if (curOpCode.slice(0, 4) === 'PUSH') { - var jumpNum = raw[pc] - 0x5f + const jumpNum = raw[pc] - 0x5f pushData = raw.slice(pc + 1, pc + jumpNum + 1) i += jumpNum } - var data = pushData.toString('hex') !== '' ? ' ' + pushData.toString('hex') : '' + const data = pushData.toString('hex') !== '' ? ' ' + pushData.toString('hex') : '' code.push(this.pad(pc, this.roundLog(raw.length, 10)) + ' ' + curOpCode + data) pushData = '' @@ -31,15 +31,15 @@ module.exports = { * information about the opcode. */ parseCode: function (raw) { - var code = [] - for (var i = 0; i < raw.length; i++) { - var opcode = opcodes(raw[i], true) + const code = [] + for (let i = 0; i < raw.length; i++) { + const opcode = opcodes(raw[i], true) if (opcode.name.slice(0, 4) === 'PUSH') { - var length = raw[i] - 0x5f + const length = raw[i] - 0x5f opcode.pushData = raw.slice(i + 1, i + length + 1) // in case pushdata extends beyond code if (i + 1 + length > raw.length) { - for (var j = opcode.pushData.length; j < length; j++) { + for (let j = opcode.pushData.length; j < length; j++) { opcode.pushData.push(0) } } @@ -51,7 +51,7 @@ module.exports = { }, pad: function (num, size) { - var s = num + '' + let s = num + '' while (s.length < size) s = '0' + s return s }, diff --git a/remix-lib/src/code/disassembler.js b/remix-lib/src/code/disassembler.js index 4c5a96b2b8..260f674b5c 100644 --- a/remix-lib/src/code/disassembler.js +++ b/remix-lib/src/code/disassembler.js @@ -1,22 +1,22 @@ 'use strict' -var parseCode = require('./codeUtils').parseCode -var util = require('../util') +const parseCode = require('./codeUtils').parseCode +const util = require('../util') -var createExpressions = function (instructions) { - var expressions = [] - var labels = 0 - for (var i = 0; i < instructions.length; i++) { - var expr = instructions[i] +const createExpressions = function (instructions) { + const expressions = [] + let labels = 0 + for (let i = 0; i < instructions.length; i++) { + const expr = instructions[i] expr.functional = false if (expr.name === 'JUMPDEST') { expr.label = 'label' + (++labels) } else if (expr.name.slice(0, 3) === 'DUP') { } else if (expr.name.slice(0, 4) === 'SWAP') { } else if (expr.out <= 1 && expr.in <= expressions.length) { - var error = false - for (var j = 0; j < expr.in && !error; j++) { - var arg = expressions[expressions.length - j - 1] + let error = false + for (let j = 0; j < expr.in && !error; j++) { + const arg = expressions[expressions.length - j - 1] if (!arg.functional || arg.out !== 1) { error = true break @@ -32,7 +32,7 @@ var createExpressions = function (instructions) { return expressions } -var toString = function (expr) { +const toString = function (expr) { if (expr.name.slice(0, 4) === 'PUSH') { return util.hexConvert(expr.pushData) } else if (expr.name === 'JUMPDEST') { @@ -44,8 +44,8 @@ var toString = function (expr) { } } -var disassemble = function (input) { - var code = parseCode(util.hexToIntArray(input)) +const disassemble = function (input) { + const code = parseCode(util.hexToIntArray(input)) return createExpressions(code).map(toString).join('\n') } diff --git a/remix-lib/src/code/opcodes.js b/remix-lib/src/code/opcodes.js index b4a856d4f9..8c841c2fc6 100644 --- a/remix-lib/src/code/opcodes.js +++ b/remix-lib/src/code/opcodes.js @@ -1,5 +1,5 @@ 'use strict' -var codes = { +const codes = { // 0x0 range - arithmetic ops // name, baseCost, off stack, on stack, dynamic, async // @todo can be improved on basis of this: https://github.com/ethereumjs/ethereumjs-vm/blob/master/lib/evm/opcodes.ts @@ -168,8 +168,8 @@ var codes = { } module.exports = function (op, full) { - var code = codes[op] ? codes[op] : ['INVALID', 0, 0, 0, false, false] - var opcode = code[0] + const code = codes[op] ? codes[op] : ['INVALID', 0, 0, 0, false, false] + let opcode = code[0] if (full) { if (opcode === 'LOG') { diff --git a/remix-lib/src/eventManager.js b/remix-lib/src/eventManager.js index ce3c8387b5..301ff2acf4 100644 --- a/remix-lib/src/eventManager.js +++ b/remix-lib/src/eventManager.js @@ -21,7 +21,7 @@ eventManager.prototype.unregister = function (eventName, obj, func) { func = obj obj = this.anonymous } - for (var reg in this.registered[eventName]) { + for (let reg in this.registered[eventName]) { if (this.registered[eventName][reg].obj === obj && this.registered[eventName][reg].func === func) { this.registered[eventName].splice(reg, 1) } @@ -61,8 +61,8 @@ eventManager.prototype.trigger = function (eventName, args) { if (!this.registered[eventName]) { return } - for (var listener in this.registered[eventName]) { - var l = this.registered[eventName][listener] + for (let listener in this.registered[eventName]) { + const l = this.registered[eventName][listener] l.func.apply(l.obj === this.anonymous ? {} : l.obj, args) } } diff --git a/remix-lib/src/execution/eventsDecoder.js b/remix-lib/src/execution/eventsDecoder.js index 5d1ff46c56..f821d19660 100644 --- a/remix-lib/src/execution/eventsDecoder.js +++ b/remix-lib/src/execution/eventsDecoder.js @@ -1,6 +1,6 @@ 'use strict' -var ethers = require('ethers') -var txHelper = require('./txHelper') +const ethers = require('ethers') +const txHelper = require('./txHelper') /** * Register to txListener and extract events @@ -37,17 +37,17 @@ class EventsDecoder { } _eventABI (contract) { - var eventABI = {} - var abi = new ethers.utils.Interface(contract.abi) - for (var e in abi.events) { - var event = abi.events[e] + const eventABI = {} + const abi = new ethers.utils.Interface(contract.abi) + for (let e in abi.events) { + const event = abi.events[e] eventABI[event.topic.replace('0x', '')] = { event: event.name, inputs: event.inputs, object: event, abi: abi } } return eventABI } _eventsABI (compiledContracts) { - var eventsABI = {} + const eventsABI = {} txHelper.visitContracts(compiledContracts, (contract) => { eventsABI[contract.name] = this._eventABI(contract.object) }) @@ -55,7 +55,7 @@ class EventsDecoder { } _event (hash, eventsABI) { - for (var k in eventsABI) { + for (let k in eventsABI) { if (eventsABI[k][hash]) { return eventsABI[k][hash] } @@ -79,16 +79,16 @@ class EventsDecoder { } _decodeEvents (tx, logs, contractName, compiledContracts, cb) { - var eventsABI = this._eventsABI(compiledContracts) - var events = [] - for (var i in logs) { + const eventsABI = this._eventsABI(compiledContracts) + const events = [] + for (let i in logs) { // [address, topics, mem] - var log = logs[i] - var topicId = log.topics[0] - var eventAbi = this._event(topicId.replace('0x', ''), eventsABI) + const log = logs[i] + const topicId = log.topics[0] + const eventAbi = this._event(topicId.replace('0x', ''), eventsABI) if (eventAbi) { - var decodedlog = eventAbi.abi.parseLog(log) - let decoded = {} + const decodedlog = eventAbi.abi.parseLog(log) + const decoded = {} for (const v in decodedlog.values) { decoded[v] = this._stringifyEvent(decodedlog.values[v]) } diff --git a/remix-lib/src/execution/execution-context.js b/remix-lib/src/execution/execution-context.js index 9394536960..f22f1a3f87 100644 --- a/remix-lib/src/execution/execution-context.js +++ b/remix-lib/src/execution/execution-context.js @@ -11,9 +11,10 @@ const LogsManager = require('./logsManager.js') const rlp = ethUtil.rlp +let web3 if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') { var injectedProvider = window.web3.currentProvider - var web3 = new Web3(injectedProvider) + web3 = new Web3(injectedProvider) } else { web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')) } @@ -36,17 +37,16 @@ class StateManagerCommonStorageDump extends StateManager { } dumpStorage (address, cb) { - var self = this - this._getStorageTrie(address, function (err, trie) { + this._getStorageTrie(address, (err, trie) => { if (err) { return cb(err) } - var storage = {} - var stream = trie.createReadStream() - stream.on('data', function (val) { - var value = rlp.decode(val.value) + const storage = {} + const stream = trie.createReadStream() + stream.on('data', (val) => { + const value = rlp.decode(val.value) storage['0x' + val.key.toString('hex')] = { - key: self.keyHashes[val.key.toString('hex')], + key: this.keyHashes[val.key.toString('hex')], value: '0x' + value.toString('hex') } }) @@ -57,7 +57,7 @@ class StateManagerCommonStorageDump extends StateManager { } getStateRoot (cb) { - let checkpoint = this._checkpointCount + const checkpoint = this._checkpointCount this._checkpointCount = 0 super.getStateRoot((err, stateRoot) => { this._checkpointCount = checkpoint @@ -76,39 +76,38 @@ class StateManagerCommonStorageDump extends StateManager { } function createVm (hardfork) { - var stateManager = new StateManagerCommonStorageDump({}) + const stateManager = new StateManagerCommonStorageDump({}) stateManager.checkpoint(() => {}) - var vm = new EthJSVM({ + const vm = new EthJSVM({ activatePrecompiles: true, blockchain: stateManager.blockchain, stateManager: stateManager, hardfork: hardfork }) vm.blockchain.validate = false - var web3vm = new Web3VMProvider() + const web3vm = new Web3VMProvider() web3vm.setVM(vm) return { vm, web3vm, stateManager } } -var vms = { +const vms = { byzantium: createVm('byzantium'), constantinople: createVm('constantinople'), petersburg: createVm('petersburg'), istanbul: createVm('istanbul') } -var mainNetGenesisHash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3' +const mainNetGenesisHash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3' /* trigger contextChanged, web3EndpointChanged */ function ExecutionContext () { - var self = this this.event = new EventManager() this.logsManager = new LogsManager() - var executionContext = null + let executionContext = null this.blockGasLimitDefault = 4300000 this.blockGasLimit = this.blockGasLimitDefault @@ -148,7 +147,7 @@ function ExecutionContext () { callback(null, { id: '-', name: 'VM' }) } else { web3.eth.net.getId((err, id) => { - var name = null + let name = null if (err) name = 'Unknown' // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md else if (id === 1) name = 'Main' @@ -172,38 +171,38 @@ function ExecutionContext () { } } - this.removeProvider = function (name) { + this.removeProvider = (name) => { if (name && this.customNetWorks[name]) { delete this.customNetWorks[name] - self.event.trigger('removeProvider', [name]) + this.event.trigger('removeProvider', [name]) } } - this.addProvider = function (network) { + this.addProvider = (network) => { if (network && network.name && network.url) { this.customNetWorks[network.name] = network - self.event.trigger('addProvider', [network]) + this.event.trigger('addProvider', [network]) } } - this.internalWeb3 = function () { + this.internalWeb3 = () => { return web3 } - this.blankWeb3 = function () { + this.blankWeb3 = () => { return blankWeb3 } - this.vm = function () { + this.vm = () => { return vms[currentFork].vm } - this.setContext = function (context, endPointUrl, confirmCb, infoCb) { + this.setContext = (context, endPointUrl, confirmCb, infoCb) => { executionContext = context this.executionContextChange(context, endPointUrl, confirmCb, infoCb) } - this.executionContextChange = function (context, endPointUrl, confirmCb, infoCb, cb) { + this.executionContextChange = (context, endPointUrl, confirmCb, infoCb, cb) => { if (!cb) cb = () => {} if (context === 'vm') { @@ -211,7 +210,7 @@ function ExecutionContext () { vms[currentFork].stateManager.revert(() => { vms[currentFork].stateManager.checkpoint(() => {}) }) - self.event.trigger('contextChanged', ['vm']) + this.event.trigger('contextChanged', ['vm']) return cb() } @@ -220,11 +219,11 @@ function ExecutionContext () { infoCb('No injected Web3 provider found. Make sure your provider (e.g. MetaMask) is active and running (when recently activated you may have to reload the page).') return cb() } else { - self.askPermission() + this.askPermission() executionContext = context web3.setProvider(injectedProvider) - self._updateBlockGasLimit() - self.event.trigger('contextChanged', ['injected']) + this._updateBlockGasLimit() + this.event.trigger('contextChanged', ['injected']) return cb() } } @@ -239,16 +238,16 @@ function ExecutionContext () { } } - this.currentblockGasLimit = function () { + this.currentblockGasLimit = () => { return this.blockGasLimit } - this.stopListenOnLastBlock = function () { + this.stopListenOnLastBlock = () => { if (this.listenOnLastBlockId) clearInterval(this.listenOnLastBlockId) this.listenOnLastBlockId = null } - this._updateBlockGasLimit = function () { + this._updateBlockGasLimit = () => { if (this.getProvider() !== 'vm') { web3.eth.getBlock('latest', (err, block) => { if (!err) { @@ -261,15 +260,17 @@ function ExecutionContext () { } } - this.listenOnLastBlock = function () { + this.listenOnLastBlock = () => { this.listenOnLastBlockId = setInterval(() => { this._updateBlockGasLimit() }, 15000) } + // TODO: remove this when this function is moved + const self = this // TODO: not used here anymore and needs to be moved function setProviderFromEndpoint (endpoint, context, cb) { - var oldProvider = web3.currentProvider + const oldProvider = web3.currentProvider if (endpoint === 'ipc') { web3.setProvider(new web3.providers.IpcProvider()) @@ -291,32 +292,32 @@ function ExecutionContext () { } this.setProviderFromEndpoint = setProviderFromEndpoint - this.txDetailsLink = function (network, hash) { + this.txDetailsLink = (network, hash) => { if (transactionDetailsLinks[network]) { return transactionDetailsLinks[network] + hash } } - this.addBlock = function (block) { + this.addBlock = (block) => { let blockNumber = '0x' + block.header.number.toString('hex') if (blockNumber === '0x') { blockNumber = '0x0' } blockNumber = web3.utils.toHex(web3.utils.toBN(blockNumber)) - self.blocks['0x' + block.hash().toString('hex')] = block - self.blocks[blockNumber] = block - self.latestBlockNumber = blockNumber + this.blocks['0x' + block.hash().toString('hex')] = block + this.blocks[blockNumber] = block + this.latestBlockNumber = blockNumber this.logsManager.checkBlock(blockNumber, block, this.web3()) } - this.trackTx = function (tx, block) { - self.txs[tx] = block + this.trackTx = (tx, block) => { + this.txs[tx] = block } } -var transactionDetailsLinks = { +const transactionDetailsLinks = { 'Main': 'https://www.etherscan.io/tx/', 'Rinkeby': 'https://rinkeby.etherscan.io/tx/', 'Ropsten': 'https://ropsten.etherscan.io/tx/', diff --git a/remix-lib/src/execution/txExecution.js b/remix-lib/src/execution/txExecution.js index 0cb68a5c8c..8aaf487e8a 100644 --- a/remix-lib/src/execution/txExecution.js +++ b/remix-lib/src/execution/txExecution.js @@ -71,7 +71,7 @@ module.exports = { STOP: 'stop', REFUND_EXHAUSTED: 'refund exhausted' } - let ret = { + const ret = { error: false, message: '' } diff --git a/remix-lib/src/execution/txFormat.js b/remix-lib/src/execution/txFormat.js index 848590e57b..8a36119059 100644 --- a/remix-lib/src/execution/txFormat.js +++ b/remix-lib/src/execution/txFormat.js @@ -1,9 +1,9 @@ 'use strict' -var ethers = require('ethers') -var helper = require('./txHelper') -var asyncJS = require('async') -var solcLinker = require('solc/linker') -var ethJSUtil = require('ethereumjs-util') +const ethers = require('ethers') +const helper = require('./txHelper') +const asyncJS = require('async') +const solcLinker = require('solc/linker') +const ethJSUtil = require('ethereumjs-util') module.exports = { @@ -15,8 +15,8 @@ module.exports = { * @param {String} contractbyteCode */ encodeData: function (funABI, values, contractbyteCode) { - var encoded - var encodedHex + let encoded + let encodedHex try { encoded = helper.encodeParams(funABI, values) encodedHex = encoded.toString('hex') @@ -38,9 +38,9 @@ module.exports = { * @param {Function} callback - callback */ encodeParams: function (params, funAbi, callback) { - var data = '' - var dataHex = '' - var funArgs + let data = '' + let dataHex = '' + let funArgs if (params.indexOf('raw:0x') === 0) { // in that case we consider that the input is already encoded and *does not* contain the method signature dataHex = params.replace('raw:0x', '') @@ -51,16 +51,14 @@ module.exports = { params = params.replace(/(^|,\s+|,)(0[xX][0-9a-fA-F]+)(\s+,|,|$)/g, '$1"$2"$3') // replace non quoted hex string by quoted hex string funArgs = JSON.parse('[' + params + ']') } catch (e) { - callback('Error encoding arguments: ' + e) - return + return callback('Error encoding arguments: ' + e) } if (funArgs.length > 0) { try { data = helper.encodeParams(funAbi, funArgs) dataHex = data.toString('hex') } catch (e) { - callback('Error encoding arguments: ' + e) - return + return callback('Error encoding arguments: ' + e) } } if (data.slice(0, 9) === 'undefined') { @@ -100,12 +98,12 @@ module.exports = { encodeConstructorCallAndLinkLibraries: function (contract, params, funAbi, linkLibraries, linkReferences, callback) { this.encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) - var bytecodeToDeploy = contract.evm.bytecode.object + let bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { if (linkLibraries && linkReferences) { - for (var libFile in linkLibraries) { - for (var lib in linkLibraries[libFile]) { - var address = linkLibraries[libFile][lib] + for (let libFile in linkLibraries) { + for (let lib in linkLibraries[libFile]) { + const address = linkLibraries[libFile][lib] if (!ethJSUtil.isValidAddress(address)) return callback(address + ' is not a valid address. Please check the provided address is valid.') bytecodeToDeploy = this.linkLibraryStandardFromlinkReferences(lib, address.replace('0x', ''), bytecodeToDeploy, linkReferences) } @@ -135,9 +133,9 @@ module.exports = { encodeConstructorCallAndDeployLibraries: function (contractName, contract, contracts, params, funAbi, callback, callbackStep, callbackDeployLibrary) { this.encodeParams(params, funAbi, (error, encodedParam) => { if (error) return callback(error) - var dataHex = '' - var contractBytecode = contract.evm.bytecode.object - var bytecodeToDeploy = contract.evm.bytecode.object + let dataHex = '' + const contractBytecode = contract.evm.bytecode.object + let bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { this.linkBytecode(contract, contracts, (err, bytecode) => { if (err) { @@ -169,9 +167,9 @@ module.exports = { * @param {Function} callbackDeployLibrary - callbackDeployLibrary */ buildData: function (contractName, contract, contracts, isConstructor, funAbi, params, callback, callbackStep, callbackDeployLibrary) { - var funArgs = [] - var data = '' - var dataHex = '' + let funArgs = [] + let data = '' + let dataHex = '' if (params.indexOf('raw:0x') === 0) { // in that case we consider that the input is already encoded and *does not* contain the method signature @@ -183,15 +181,13 @@ module.exports = { funArgs = this.parseFunctionParams(params) } } catch (e) { - callback('Error encoding arguments: ' + e) - return + return callback('Error encoding arguments: ' + e) } try { data = helper.encodeParams(funAbi, funArgs) dataHex = data.toString('hex') } catch (e) { - callback('Error encoding arguments: ' + e) - return + return callback('Error encoding arguments: ' + e) } if (data.slice(0, 9) === 'undefined') { dataHex = data.slice(9) @@ -200,10 +196,10 @@ module.exports = { dataHex = data.slice(2) } } - var contractBytecode + let contractBytecode if (isConstructor) { contractBytecode = contract.evm.bytecode.object - var bytecodeToDeploy = contract.evm.bytecode.object + let bytecodeToDeploy = contract.evm.bytecode.object if (bytecodeToDeploy.indexOf('_') >= 0) { this.linkBytecode(contract, contracts, (err, bytecode) => { if (err) { @@ -226,16 +222,16 @@ module.exports = { atAddress: function () {}, linkBytecodeStandard: function (contract, contracts, callback, callbackStep, callbackDeployLibrary) { - var contractBytecode = contract.evm.bytecode.object + let contractBytecode = contract.evm.bytecode.object asyncJS.eachOfSeries(contract.evm.bytecode.linkReferences, (libs, file, cbFile) => { asyncJS.eachOfSeries(contract.evm.bytecode.linkReferences[file], (libRef, libName, cbLibDeployed) => { - var library = contracts[file][libName] + const library = contracts[file][libName] if (library) { this.deployLibrary(file + ':' + libName, libName, library, contracts, (error, address) => { if (error) { return cbLibDeployed(error) } - var hexAddress = address.toString('hex') + let hexAddress = address.toString('hex') if (hexAddress.slice(0, 2) === '0x') { hexAddress = hexAddress.slice(2) } @@ -257,21 +253,21 @@ module.exports = { }, linkBytecodeLegacy: function (contract, contracts, callback, callbackStep, callbackDeployLibrary) { - var libraryRefMatch = contract.evm.bytecode.object.match(/__([^_]{1,36})__/) + const libraryRefMatch = contract.evm.bytecode.object.match(/__([^_]{1,36})__/) if (!libraryRefMatch) { return callback('Invalid bytecode format.') } - var libraryName = libraryRefMatch[1] + const libraryName = libraryRefMatch[1] // file_name:library_name - var libRef = libraryName.match(/(.*):(.*)/) + const libRef = libraryName.match(/(.*):(.*)/) if (!libRef) { return callback('Cannot extract library reference ' + libraryName) } if (!contracts[libRef[1]] || !contracts[libRef[1]][libRef[2]]) { return callback('Cannot find library reference ' + libraryName) } - var libraryShortName = libRef[2] - var library = contracts[libRef[1]][libraryShortName] + const libraryShortName = libRef[2] + const library = contracts[libRef[1]][libraryShortName] if (!library) { return callback('Library ' + libraryName + ' not found.') } @@ -279,7 +275,7 @@ module.exports = { if (err) { return callback(err) } - var hexAddress = address.toString('hex') + let hexAddress = address.toString('hex') if (hexAddress.slice(0, 2) === '0x') { hexAddress = hexAddress.slice(2) } @@ -300,11 +296,11 @@ module.exports = { }, deployLibrary: function (libraryName, libraryShortName, library, contracts, callback, callbackStep, callbackDeployLibrary) { - var address = library.address + const address = library.address if (address) { return callback(null, address) } - var bytecode = library.evm.bytecode.object + const bytecode = library.evm.bytecode.object if (bytecode.indexOf('_') >= 0) { this.linkBytecode(library, contracts, (err, bytecode) => { if (err) callback(err) @@ -315,12 +311,12 @@ module.exports = { }, callbackStep, callbackDeployLibrary) } else { callbackStep(`creation of library ${libraryName} pending...`) - var data = {dataHex: bytecode, funAbi: {type: 'constructor'}, funArgs: [], contractBytecode: bytecode, contractName: libraryShortName} + const data = {dataHex: bytecode, funAbi: {type: 'constructor'}, funArgs: [], contractBytecode: bytecode, contractName: libraryShortName} callbackDeployLibrary({ data: data, useCall: false }, (err, txResult) => { if (err) { return callback(err) } - var address = txResult.result.createdAddress || txResult.result.contractAddress + const address = txResult.result.createdAddress || txResult.result.contractAddress library.address = address callback(err, address) }) @@ -328,8 +324,8 @@ module.exports = { }, linkLibraryStandardFromlinkReferences: function (libraryName, address, bytecode, linkReferences) { - for (var file in linkReferences) { - for (var libName in linkReferences[file]) { + for (let file in linkReferences) { + for (let libName in linkReferences[file]) { if (libraryName === libName) { bytecode = this.setLibraryAddress(address, bytecode, linkReferences[file][libName]) } @@ -344,8 +340,8 @@ module.exports = { setLibraryAddress: function (address, bytecodeToLink, positions) { if (positions) { - for (var pos of positions) { - var regpos = bytecodeToLink.match(new RegExp(`(.{${2 * pos.start}})(.{${2 * pos.length}})(.*)`)) + for (let pos of positions) { + const regpos = bytecodeToLink.match(new RegExp(`(.{${2 * pos.start}})(.{${2 * pos.length}})(.*)`)) if (regpos) { bytecodeToLink = regpos[1] + address + regpos[3] } @@ -362,22 +358,22 @@ module.exports = { // Only decode if there supposed to be fields if (fnabi.outputs && fnabi.outputs.length > 0) { try { - var i + let i - var outputTypes = [] + const outputTypes = [] for (i = 0; i < fnabi.outputs.length; i++) { - var type = fnabi.outputs[i].type + const type = fnabi.outputs[i].type outputTypes.push(type.indexOf('tuple') === 0 ? helper.makeFullTypeDefinition(fnabi.outputs[i]) : type) } if (!response.length) response = new Uint8Array(32 * fnabi.outputs.length) // ensuring the data is at least filled by 0 cause `AbiCoder` throws if there's not engouh data // decode data - var abiCoder = new ethers.utils.AbiCoder() - var decodedObj = abiCoder.decode(outputTypes, response) + const abiCoder = new ethers.utils.AbiCoder() + const decodedObj = abiCoder.decode(outputTypes, response) - var json = {} + const json = {} for (i = 0; i < outputTypes.length; i++) { - var name = fnabi.outputs[i].name + const name = fnabi.outputs[i].name json[i] = outputTypes[i] + ': ' + (name ? name + ' ' + decodedObj[i] : decodedObj[i]) } diff --git a/remix-lib/src/execution/txHelper.js b/remix-lib/src/execution/txHelper.js index 4c4c161109..9e2e54786c 100644 --- a/remix-lib/src/execution/txHelper.js +++ b/remix-lib/src/execution/txHelper.js @@ -1,20 +1,20 @@ 'use strict' -var ethers = require('ethers') +const ethers = require('ethers') module.exports = { makeFullTypeDefinition: function (typeDef) { if (typeDef && typeDef.type.indexOf('tuple') === 0 && typeDef.components) { - var innerTypes = typeDef.components.map((innerType) => { return this.makeFullTypeDefinition(innerType) }) + const innerTypes = typeDef.components.map((innerType) => { return this.makeFullTypeDefinition(innerType) }) return `tuple(${innerTypes.join(',')})${this.extractSize(typeDef.type)}` } return typeDef.type }, encodeParams: function (funABI, args) { - var types = [] + const types = [] if (funABI.inputs && funABI.inputs.length) { - for (var i = 0; i < funABI.inputs.length; i++) { - var type = funABI.inputs[i].type + for (let i = 0; i < funABI.inputs.length; i++) { + const type = funABI.inputs[i].type // "false" will be converting to `false` and "true" will be working // fine as abiCoder assume anything in quotes as `true` if (type === 'bool' && args[i] === 'false') { @@ -29,13 +29,13 @@ module.exports = { // NOTE: the caller will concatenate the bytecode and this // it could be done here too for consistency - var abiCoder = new ethers.utils.AbiCoder() + const abiCoder = new ethers.utils.AbiCoder() return abiCoder.encode(types, args) }, encodeFunctionId: function (funABI) { if (funABI.type === 'fallback') return '0x' - var abi = new ethers.utils.Interface([funABI]) + let abi = new ethers.utils.Interface([funABI]) abi = abi.functions[funABI.name] return abi.sighash }, @@ -63,7 +63,7 @@ module.exports = { }, getConstructorInterface: function (abi) { - var funABI = { 'name': '', 'inputs': [], 'type': 'constructor', 'payable': 'false', 'outputs': [] } + const funABI = { 'name': '', 'inputs': [], 'type': 'constructor', 'payable': 'false', 'outputs': [] } if (typeof abi === 'string') { try { abi = JSON.parse(abi) @@ -73,7 +73,7 @@ module.exports = { } } - for (var i = 0; i < abi.length; i++) { + for (let i = 0; i < abi.length; i++) { if (abi[i].type === 'constructor') { funABI.inputs = abi[i].inputs || [] funABI.payable = abi[i].payable @@ -86,7 +86,7 @@ module.exports = { }, serializeInputs: function (fnAbi) { - var serialized = '(' + let serialized = '(' if (fnAbi.inputs && fnAbi.inputs.length) { serialized += fnAbi.inputs.map((input) => { return input.type }).join(',') } @@ -95,13 +95,13 @@ module.exports = { }, extractSize: function (type) { - var size = type.match(/([a-zA-Z0-9])(\[.*\])/) + const size = type.match(/([a-zA-Z0-9])(\[.*\])/) return size ? size[2] : '' }, getFunction: function (abi, fnName) { - for (var i = 0; i < abi.length; i++) { - var fn = abi[i] + for (let i = 0; i < abi.length; i++) { + const fn = abi[i] if (fn.type === 'function' && fnName === fn.name + '(' + fn.inputs.map((value) => { if (value.components) { let fullType = this.makeFullTypeDefinition(value) @@ -117,7 +117,7 @@ module.exports = { }, getFallbackInterface: function (abi) { - for (var i = 0; i < abi.length; i++) { + for (let i = 0; i < abi.length; i++) { if (abi[i].type === 'fallback') { return abi[i] } @@ -131,7 +131,7 @@ module.exports = { * @returns contract obj and associated file: { contract, file } or null */ getContract: (contractName, contracts) => { - for (var file in contracts) { + for (let file in contracts) { if (contracts[file][contractName]) { return { object: contracts[file][contractName], file: file } } @@ -145,17 +145,16 @@ module.exports = { * @param {Function} cb - callback */ visitContracts: (contracts, cb) => { - for (var file in contracts) { - for (var name in contracts[file]) { + for (let file in contracts) { + for (let name in contracts[file]) { if (cb({ name: name, object: contracts[file][name], file: file })) return } } }, inputParametersDeclarationToString: function (abiinputs) { - var inputs = (abiinputs || []).map((inp) => inp.type + ' ' + inp.name) + const inputs = (abiinputs || []).map((inp) => inp.type + ' ' + inp.name) return inputs.join(', ') } } - diff --git a/remix-lib/src/execution/txListener.js b/remix-lib/src/execution/txListener.js index 12a2b42d4a..60ccaa633c 100644 --- a/remix-lib/src/execution/txListener.js +++ b/remix-lib/src/execution/txListener.js @@ -1,13 +1,13 @@ 'use strict' -var async = require('async') -var ethers = require('ethers') -var ethJSUtil = require('ethereumjs-util') -var EventManager = require('../eventManager') -var codeUtil = require('../util') +const async = require('async') +const ethers = require('ethers') +const ethJSUtil = require('ethereumjs-util') +const EventManager = require('../eventManager') +const codeUtil = require('../util') -var defaultExecutionContext = require('./execution-context') -var txFormat = require('./txFormat') -var txHelper = require('./txHelper') +const defaultExecutionContext = require('./execution-context') +const txFormat = require('./txFormat') +const txHelper = require('./txHelper') /** * poll web3 each 2s if web3 @@ -17,6 +17,7 @@ var txHelper = require('./txHelper') * */ class TxListener { + constructor (opt, executionContext) { this.event = new EventManager() // has a default for now for backwards compatability @@ -43,7 +44,7 @@ class TxListener { if (!this._isListening) return // we don't listen if (this._loopId && this.executionContext.getProvider() !== 'vm') return // we seems to already listen on a "web3" network - var call = { + const call = { from: from, to: to, input: data, @@ -144,13 +145,13 @@ class TxListener { _startListenOnNetwork () { this._loopId = setInterval(() => { - var currentLoopId = this._loopId + const currentLoopId = this._loopId this.executionContext.web3().eth.getBlockNumber((error, blockNumber) => { if (this._loopId === null) return if (error) return console.log(error) if (currentLoopId === this._loopId && (!this.lastBlock || blockNumber > this.lastBlock)) { if (!this.lastBlock) this.lastBlock = blockNumber - 1 - var current = this.lastBlock + 1 + let current = this.lastBlock + 1 this.lastBlock = blockNumber while (blockNumber >= current) { try { @@ -219,18 +220,18 @@ class TxListener { } _resolveTx (tx, receipt, cb) { - var contracts = this._api.contracts() + const contracts = this._api.contracts() if (!contracts) return cb() - var contractName - var fun + let contractName + let fun if (!tx.to || tx.to === '0x0') { // testrpc returns 0x0 in that case // contract creation / resolve using the creation bytes code // if web3: we have to call getTransactionReceipt to get the created address // if VM: created address already included - var code = tx.input + const code = tx.input contractName = this._tryResolveContract(code, contracts, true) if (contractName) { - var address = receipt.contractAddress + let address = receipt.contractAddress this._resolvedContracts[address] = contractName fun = this._resolveFunction(contractName, contracts, tx, true) if (this._resolvedTransactions[tx.hash]) { @@ -246,10 +247,10 @@ class TxListener { this.executionContext.web3().eth.getCode(tx.to, (error, code) => { if (error) return cb(error) if (code) { - var contractName = this._tryResolveContract(code, contracts, false) + const contractName = this._tryResolveContract(code, contracts, false) if (contractName) { this._resolvedContracts[tx.to] = contractName - var fun = this._resolveFunction(contractName, contracts, tx, false) + const fun = this._resolveFunction(contractName, contracts, tx, false) return cb(null, {to: tx.to, contractName: contractName, function: fun}) } } @@ -266,18 +267,18 @@ class TxListener { } _resolveFunction (contractName, compiledContracts, tx, isCtor) { - var contract = txHelper.getContract(contractName, compiledContracts) + const contract = txHelper.getContract(contractName, compiledContracts) if (!contract) { console.log('txListener: cannot resolve ' + contractName) return } - var abi = contract.object.abi - var inputData = tx.input.replace('0x', '') + const abi = contract.object.abi + const inputData = tx.input.replace('0x', '') if (!isCtor) { - var methodIdentifiers = contract.object.evm.methodIdentifiers - for (var fn in methodIdentifiers) { + const methodIdentifiers = contract.object.evm.methodIdentifiers + for (let fn in methodIdentifiers) { if (methodIdentifiers[fn] === inputData.substring(0, 8)) { - var fnabi = txHelper.getFunction(abi, fn) + const fnabi = txHelper.getFunction(abi, fn) this._resolvedTransactions[tx.hash] = { contractName: contractName, to: tx.to, @@ -298,8 +299,8 @@ class TxListener { params: null } } else { - var bytecode = contract.object.evm.bytecode.object - var params = null + const bytecode = contract.object.evm.bytecode.object + let params = null if (bytecode && bytecode.length) { params = this._decodeInputParams(inputData.substring(bytecode.length), txHelper.getConstructorInterface(abi)) } @@ -314,9 +315,9 @@ class TxListener { } _tryResolveContract (codeToResolve, compiledContracts, isCreation) { - var found = null + let found = null txHelper.visitContracts(compiledContracts, (contract) => { - var bytes = isCreation ? contract.object.evm.bytecode.object : contract.object.evm.deployedBytecode.object + const bytes = isCreation ? contract.object.evm.bytecode.object : contract.object.evm.deployedBytecode.object if (codeUtil.compareByteCode(codeToResolve, '0x' + bytes)) { found = contract.name return true @@ -329,14 +330,14 @@ class TxListener { data = ethJSUtil.toBuffer('0x' + data) if (!data.length) data = new Uint8Array(32 * abi.inputs.length) // ensuring the data is at least filled by 0 cause `AbiCoder` throws if there's not engouh data - var inputTypes = [] - for (var i = 0; i < abi.inputs.length; i++) { - var type = abi.inputs[i].type + const inputTypes = [] + for (let i = 0; i < abi.inputs.length; i++) { + const type = abi.inputs[i].type inputTypes.push(type.indexOf('tuple') === 0 ? txHelper.makeFullTypeDefinition(abi.inputs[i]) : type) } - var abiCoder = new ethers.utils.AbiCoder() - var decoded = abiCoder.decode(inputTypes, data) - var ret = {} + const abiCoder = new ethers.utils.AbiCoder() + const decoded = abiCoder.decode(inputTypes, data) + const ret = {} for (var k in abi.inputs) { ret[abi.inputs[k].type + ' ' + abi.inputs[k].name] = decoded[k] } diff --git a/remix-lib/src/execution/txRunner.js b/remix-lib/src/execution/txRunner.js index ee933e1af2..9c8fd59d98 100644 --- a/remix-lib/src/execution/txRunner.js +++ b/remix-lib/src/execution/txRunner.js @@ -1,10 +1,10 @@ 'use strict' -var EthJSTX = require('ethereumjs-tx').Transaction -var EthJSBlock = require('ethereumjs-block') -var ethJSUtil = require('ethereumjs-util') -var BN = ethJSUtil.BN -var defaultExecutionContext = require('./execution-context') -var EventManager = require('../eventManager') +const EthJSTX = require('ethereumjs-tx').Transaction +const EthJSBlock = require('ethereumjs-block') +const ethJSUtil = require('ethereumjs-util') +const BN = ethJSUtil.BN +const defaultExecutionContext = require('./execution-context') +const EventManager = require('../eventManager') class TxRunner { constructor (vmaccounts, api, executionContext) { @@ -26,7 +26,7 @@ class TxRunner { } rawRun (args, confirmationCb, gasEstimationForceSend, promptCb, cb) { - var timestamp = Date.now() + let timestamp = Date.now() if (args.timestamp) { timestamp = args.timestamp } @@ -50,15 +50,14 @@ class TxRunner { } _sendTransaction (sendTx, tx, pass, callback) { - var self = this - var cb = function (err, resp) { + const cb = (err, resp) => { if (err) { return callback(err, resp) } - self.event.trigger('transactionBroadcasted', [resp]) + this.event.trigger('transactionBroadcasted', [resp]) var listenOnResponse = () => { return new Promise(async (resolve, reject) => { - var result = await tryTillReceiptAvailable(resp) + const result = await tryTillReceiptAvailable(resp) tx = await tryTillTxAvailable(resp) resolve({ result, @@ -69,7 +68,7 @@ class TxRunner { } listenOnResponse().then((txData) => { callback(null, txData) }).catch((error) => { callback(error) }) } - var args = pass !== null ? [tx, pass, cb] : [tx, cb] + const args = pass !== null ? [tx, pass, cb] : [tx, cb] try { sendTx.apply({}, args) } catch (e) { @@ -78,18 +77,16 @@ class TxRunner { } execute (args, confirmationCb, gasEstimationForceSend, promptCb, callback) { - var self = this - - var data = args.data + let data = args.data if (data.slice(0, 2) !== '0x') { data = '0x' + data } if (!this.executionContext.isVM()) { - self.runInNode(args.from, args.to, data, args.value, args.gasLimit, args.useCall, confirmationCb, gasEstimationForceSend, promptCb, callback) + this.runInNode(args.from, args.to, data, args.value, args.gasLimit, args.useCall, confirmationCb, gasEstimationForceSend, promptCb, callback) } else { try { - self.runInVm(args.from, args.to, data, args.value, args.gasLimit, args.useCall, args.timestamp, callback) + this.runInVm(args.from, args.to, data, args.value, args.gasLimit, args.useCall, args.timestamp, callback) } catch (e) { callback(e, null) } @@ -165,8 +162,7 @@ class TxRunner { } runInNode (from, to, data, value, gasLimit, useCall, confirmCb, gasEstimationForceSend, promptCb, callback) { - const self = this - var tx = { from: from, to: to, data: data, value: value } + const tx = { from: from, to: to, data: data, value: value } if (useCall) { tx.gas = gasLimit @@ -177,34 +173,34 @@ class TxRunner { }) }) } - this.executionContext.web3().eth.estimateGas(tx, function (err, gasEstimation) { + this.executionContext.web3().eth.estimateGas(tx, (err, gasEstimation) => { gasEstimationForceSend(err, () => { // callback is called whenever no error tx.gas = !gasEstimation ? gasLimit : gasEstimation - if (self._api.config.getUnpersistedProperty('doNotShowTransactionConfirmationAgain')) { - return self._executeTx(tx, null, self._api, promptCb, callback) + if (this._api.config.getUnpersistedProperty('doNotShowTransactionConfirmationAgain')) { + return this._executeTx(tx, null, this._api, promptCb, callback) } - self._api.detectNetwork((err, network) => { + this._api.detectNetwork((err, network) => { if (err) { console.log(err) return } confirmCb(network, tx, tx.gas, (gasPrice) => { - return self._executeTx(tx, gasPrice, self._api, promptCb, callback) + return this._executeTx(tx, gasPrice, this._api, promptCb, callback) }, (error) => { callback(error) }) }) }, () => { - var blockGasLimit = self.executionContext.currentblockGasLimit() + const blockGasLimit = this.executionContext.currentblockGasLimit() // NOTE: estimateGas very likely will return a large limit if execution of the code failed // we want to be able to run the code in order to debug and find the cause for the failure if (err) return callback(err) - var warnEstimation = ' An important gas estimation might also be the sign of a problem in the contract code. Please check loops and be sure you did not sent value to a non payable function (that\'s also the reason of strong gas estimation). ' + let warnEstimation = ' An important gas estimation might also be the sign of a problem in the contract code. Please check loops and be sure you did not sent value to a non payable function (that\'s also the reason of strong gas estimation). ' warnEstimation += ' ' + err if (gasEstimation > gasLimit) { @@ -257,7 +253,7 @@ function run (self, tx, stamp, confirmationCb, gasEstimationForceSend, promptCb, delete self.pendingTxs[stamp] callback(error, result) if (self.queusTxs.length) { - var next = self.queusTxs.pop() + const next = self.queusTxs.pop() run(self, next.tx, next.stamp, next.callback) } }) diff --git a/remix-lib/src/execution/typeConversion.js b/remix-lib/src/execution/typeConversion.js index 1b5d879fc3..04559eb8f6 100644 --- a/remix-lib/src/execution/typeConversion.js +++ b/remix-lib/src/execution/typeConversion.js @@ -1,6 +1,6 @@ 'use strict' -var ethJSUtil = require('ethereumjs-util') -var BN = ethJSUtil.BN +const ethJSUtil = require('ethereumjs-util') +const BN = ethJSUtil.BN module.exports = { toInt: (h) => { @@ -17,7 +17,7 @@ module.exports = { function stringify (v) { try { if (v instanceof Array) { - var ret = [] + const ret = [] for (var k in v) { ret.push(stringify(v[k])) } @@ -27,8 +27,8 @@ function stringify (v) { } else if (v._isBuffer) { return ethJSUtil.bufferToHex(v) } else if (typeof v === 'object') { - var retObject = {} - for (var i in v) { + const retObject = {} + for (let i in v) { retObject[i] = stringify(v[i]) } return retObject diff --git a/remix-lib/src/helpers/traceHelper.js b/remix-lib/src/helpers/traceHelper.js index 7c19322681..2c1eb189a3 100644 --- a/remix-lib/src/helpers/traceHelper.js +++ b/remix-lib/src/helpers/traceHelper.js @@ -1,13 +1,14 @@ 'use strict' -var ui = require('./uiHelper') +const ui = require('./uiHelper') + module.exports = { // vmTraceIndex has to point to a CALL, CODECALL, ... resolveCalledAddress: function (vmTraceIndex, trace) { - var step = trace[vmTraceIndex] + const step = trace[vmTraceIndex] if (this.isCreateInstruction(step)) { return this.contractCreationToken(vmTraceIndex) } else if (this.isCallInstruction(step)) { - var stack = step.stack // callcode, delegatecall, ... + const stack = step.stack // callcode, delegatecall, ... return ui.normalizeHexAddress(stack[stack.length - 2]) } return undefined @@ -51,7 +52,7 @@ module.exports = { isCallToPrecompiledContract: function (index, trace) { // if stack empty => this is not a precompiled contract - var step = trace[index] + const step = trace[index] if (this.isCallInstruction(step)) { return index + 1 < trace.length && trace[index + 1].stack.length !== 0 } else { diff --git a/remix-lib/src/helpers/uiHelper.js b/remix-lib/src/helpers/uiHelper.js index 9ee89e0b1e..de996700e4 100644 --- a/remix-lib/src/helpers/uiHelper.js +++ b/remix-lib/src/helpers/uiHelper.js @@ -1,7 +1,7 @@ 'use strict' module.exports = { formatMemory: function (mem, width) { - var ret = {} + const ret = {} if (!mem) { return ret } @@ -10,19 +10,19 @@ module.exports = { mem = mem.join('') // geth returns an array, eth return raw string } - for (var k = 0; k < mem.length; k += (width * 2)) { - var memory = mem.substr(k, width * 2) - var content = this.tryConvertAsciiFormat(memory) + for (let k = 0; k < mem.length; k += (width * 2)) { + const memory = mem.substr(k, width * 2) + const content = this.tryConvertAsciiFormat(memory) ret['0x' + (k / 2).toString(16)] = content.raw + '\t' + content.ascii } return ret }, tryConvertAsciiFormat: function (memorySlot) { - var ret = { ascii: '', raw: '' } - for (var k = 0; k < memorySlot.length; k += 2) { - var raw = memorySlot.substr(k, 2) - var ascii = String.fromCharCode(parseInt(raw, 16)) + const ret = { ascii: '', raw: '' } + for (let k = 0; k < memorySlot.length; k += 2) { + const raw = memorySlot.substr(k, 2) + let ascii = String.fromCharCode(parseInt(raw, 16)) ascii = ascii.replace(/[^\w\s]/, '?') if (ascii === '') { ascii = '?' @@ -45,9 +45,9 @@ module.exports = { * used if multiple occurences of the same key is needed */ formatCss: function (css1, css2) { - var ret = '' - for (var arg in arguments) { - for (var k in arguments[arg]) { + let ret = '' + for (let arg in arguments) { + for (let k in arguments[arg]) { if (arguments[arg][k] && ret.indexOf(k) === -1) { if (k.indexOf('*') === 0) { ret += arguments[arg][k] @@ -71,7 +71,7 @@ module.exports = { normalizeHexAddress: function (hex) { if (hex.indexOf('0x') === 0) hex = hex.replace('0x', '') if (hex.length >= 40) { - var reg = /(.{40})$/.exec(hex) + const reg = /(.{40})$/.exec(hex) if (reg) { return '0x' + reg[0] } diff --git a/remix-lib/src/init.js b/remix-lib/src/init.js index 4594f3a00f..8dec8615e7 100644 --- a/remix-lib/src/init.js +++ b/remix-lib/src/init.js @@ -1,10 +1,10 @@ 'use strict' -var Web3 = require('web3') +const Web3 = require('web3') module.exports = { loadWeb3: function (url) { if (!url) url = 'http://localhost:8545' - var web3 = new Web3() + const web3 = new Web3() web3.setProvider(new web3.providers.HttpProvider(url)) this.extend(web3) return web3 @@ -30,7 +30,7 @@ module.exports = { return } // DEBUG - var methods = [] + const methods = [] if (!(web3.debug && web3.debug.preimage)) { methods.push(new web3.extend.Method({ name: 'preimage', @@ -67,7 +67,7 @@ module.exports = { } } -var web3DebugNodes = { +const web3DebugNodes = { 'Main': 'https://mainnet.infura.io/remix', 'Rinkeby': 'https://remix-rinkeby.ethdevops.io', 'Ropsten': 'https://remix-ropsten.ethdevops.io', diff --git a/remix-lib/src/offsetToLineColumnConverter.js b/remix-lib/src/offsetToLineColumnConverter.js index b69731b3b6..fbc2bd4436 100644 --- a/remix-lib/src/offsetToLineColumnConverter.js +++ b/remix-lib/src/offsetToLineColumnConverter.js @@ -1,12 +1,12 @@ 'use strict' -var SourceMappingDecoder = require('./sourceMappingDecoder') +const SourceMappingDecoder = require('./sourceMappingDecoder') function offsetToColumnConverter (compilerEvent) { this.lineBreakPositionsByContent = {} this.sourceMappingDecoder = new SourceMappingDecoder() var self = this if (compilerEvent) { - compilerEvent.register('compilationFinished', function (success, data, source) { + compilerEvent.register('compilationFinished', (success, data, source) => { self.clear() }) } @@ -14,8 +14,8 @@ function offsetToColumnConverter (compilerEvent) { offsetToColumnConverter.prototype.offsetToLineColumn = function (rawLocation, file, sources, asts) { if (!this.lineBreakPositionsByContent[file]) { - for (var filename in asts) { - var source = asts[filename] + for (let filename in asts) { + const source = asts[filename] // source id was string before. in newer versions it has been changed to an integer so we need to check the type here if (typeof source.id === 'string') source.id = parseInt(source.id, 10) if (source.id === file) { diff --git a/remix-lib/src/sourceLocationTracker.js b/remix-lib/src/sourceLocationTracker.js index 0309faa2af..f8ee6c49e6 100644 --- a/remix-lib/src/sourceLocationTracker.js +++ b/remix-lib/src/sourceLocationTracker.js @@ -1,8 +1,8 @@ 'use strict' -var EventManager = require('./eventManager') -var helper = require('./helpers/traceHelper') -var SourceMappingDecoder = require('./sourceMappingDecoder') -var util = require('./util') +const EventManager = require('./eventManager') +const helper = require('./helpers/traceHelper') +const SourceMappingDecoder = require('./sourceMappingDecoder') +const util = require('./util') /** * Process the source code location for the current executing bytecode @@ -23,12 +23,11 @@ function SourceLocationTracker (_codeManager) { * @param {Function} cb - callback function */ SourceLocationTracker.prototype.getSourceLocationFromInstructionIndex = function (address, index, contracts, cb) { - var self = this - extractSourceMap(this, this.codeManager, address, contracts, function (error, sourceMap) { + extractSourceMap(this, this.codeManager, address, contracts, (error, sourceMap) => { if (error) { cb(error) } else { - cb(null, self.sourceMappingDecoder.atIndex(index, sourceMap)) + cb(null, this.sourceMappingDecoder.atIndex(index, sourceMap)) } }) } @@ -42,14 +41,13 @@ SourceLocationTracker.prototype.getSourceLocationFromInstructionIndex = function * @param {Function} cb - callback function */ SourceLocationTracker.prototype.getSourceLocationFromVMTraceIndex = function (address, vmtraceStepIndex, contracts, cb) { - var self = this - extractSourceMap(this, this.codeManager, address, contracts, function (error, sourceMap) { + extractSourceMap(this, this.codeManager, address, contracts, (error, sourceMap) => { if (!error) { - self.codeManager.getInstructionIndex(address, vmtraceStepIndex, function (error, index) { + this.codeManager.getInstructionIndex(address, vmtraceStepIndex, (error, index) => { if (error) { cb(error) } else { - cb(null, self.sourceMappingDecoder.atIndex(index, sourceMap)) + cb(null, this.sourceMappingDecoder.atIndex(index, sourceMap)) } }) } else { @@ -63,10 +61,10 @@ SourceLocationTracker.prototype.clearCache = function () { } function getSourceMap (address, code, contracts) { - var isCreation = helper.isContractCreation(address) - var bytes - for (var file in contracts) { - for (var contract in contracts[file]) { + const isCreation = helper.isContractCreation(address) + let bytes + for (let file in contracts) { + for (let contract in contracts[file]) { bytes = isCreation ? contracts[file][contract].evm.bytecode.object : contracts[file][contract].evm.deployedBytecode.object if (util.compareByteCode(code, '0x' + bytes)) { return isCreation ? contracts[file][contract].evm.bytecode.sourceMap : contracts[file][contract].evm.deployedBytecode.sourceMap @@ -79,9 +77,9 @@ function getSourceMap (address, code, contracts) { function extractSourceMap (self, codeManager, address, contracts, cb) { if (self.sourceMapByAddress[address]) return cb(null, self.sourceMapByAddress[address]) - codeManager.getCode(address, function (error, result) { + codeManager.getCode(address, (error, result) => { if (!error) { - var sourceMap = getSourceMap(address, result.bytecode, contracts) + const sourceMap = getSourceMap(address, result.bytecode, contracts) if (sourceMap) { if (!helper.isContractCreation(address)) self.sourceMapByAddress[address] = sourceMap cb(null, sourceMap) diff --git a/remix-lib/src/sourceMappingDecoder.js b/remix-lib/src/sourceMappingDecoder.js index 602697cf81..0b42a85e37 100644 --- a/remix-lib/src/sourceMappingDecoder.js +++ b/remix-lib/src/sourceMappingDecoder.js @@ -1,6 +1,6 @@ 'use strict' -var util = require('./util') -var AstWalker = require('./astWalker') +const util = require('./util') +const AstWalker = require('./astWalker') /** * Decompress the source mapping given by solc-bin.js @@ -51,11 +51,11 @@ SourceMappingDecoder.prototype.decode = function (value) { * @return {Array} returns the decompressed source mapping. Array of {start, length, file, jump} */ SourceMappingDecoder.prototype.decompressAll = function (mapping) { - var map = mapping.split(';') - var ret = [] - for (var k in map) { - var compressed = map[k].split(':') - var sourceMap = { + const map = mapping.split(';') + const ret = [] + for (let k in map) { + const compressed = map[k].split(':') + const sourceMap = { start: compressed[0] ? parseInt(compressed[0]) : ret[ret.length - 1].start, length: compressed[1] ? parseInt(compressed[1]) : ret[ret.length - 1].length, file: compressed[2] ? parseInt(compressed[2]) : ret[ret.length - 1].file, @@ -73,8 +73,8 @@ SourceMappingDecoder.prototype.decompressAll = function (mapping) { * @return {Array} returns an array containing offset of line breaks */ SourceMappingDecoder.prototype.getLinebreakPositions = function (source) { - var ret = [] - for (var pos = source.indexOf('\n'); pos >= 0; pos = source.indexOf('\n', pos + 1)) { + const ret = [] + for (let pos = source.indexOf('\n'); pos >= 0; pos = source.indexOf('\n', pos + 1)) { ret.push(pos) } return ret @@ -112,12 +112,12 @@ SourceMappingDecoder.prototype.convertOffsetToLineColumn = function (sourceLocat SourceMappingDecoder.prototype.findNodeAtInstructionIndex = findNodeAtInstructionIndex function convertFromCharPosition (pos, lineBreakPositions) { - var line = util.findLowerBound(pos, lineBreakPositions) + let line = util.findLowerBound(pos, lineBreakPositions) if (lineBreakPositions[line] !== pos) { line = line + 1 } - var beginColumn = line === 0 ? 0 : (lineBreakPositions[line - 1] + 1) - var column = pos - beginColumn + const beginColumn = line === 0 ? 0 : (lineBreakPositions[line - 1] + 1) + const column = pos - beginColumn return { line: line, column: column @@ -126,7 +126,7 @@ function convertFromCharPosition (pos, lineBreakPositions) { function sourceLocationFromAstNode (astNode) { if (astNode.src) { - var split = astNode.src.split(':') + const split = astNode.src.split(':') return { start: parseInt(split[0]), length: parseInt(split[1]), @@ -137,16 +137,16 @@ function sourceLocationFromAstNode (astNode) { } function findNodeAtInstructionIndex (astNodeType, instIndex, sourceMap, ast) { - var sourceLocation = atIndex(instIndex, sourceMap) + const sourceLocation = atIndex(instIndex, sourceMap) return findNodeAtSourceLocation(astNodeType, sourceLocation, ast) } function findNodeAtSourceLocation (astNodeType, sourceLocation, ast) { - var astWalker = new AstWalker() - var callback = {} - var found = null + const astWalker = new AstWalker() + const callback = {} + let found = null callback['*'] = function (node) { - var nodeLocation = sourceLocationFromAstNode(node) + const nodeLocation = sourceLocationFromAstNode(node) if (!nodeLocation) { return true } @@ -166,9 +166,9 @@ function findNodeAtSourceLocation (astNodeType, sourceLocation, ast) { } function nodesAtPosition (astNodeType, position, ast) { - var astWalker = new AstWalker() - var callback = {} - var found = [] + const astWalker = new AstWalker() + const callback = {} + const found = [] callback['*'] = function (node) { var nodeLocation = sourceLocationFromAstNode(node) if (!nodeLocation) { @@ -189,13 +189,13 @@ function nodesAtPosition (astNodeType, position, ast) { } function atIndex (index, mapping) { - var ret = {} - var map = mapping.split(';') + const ret = {} + const map = mapping.split(';') if (index >= map.length) { index = map.length - 1 } - for (var k = index; k >= 0; k--) { - var current = map[k] + for (let k = index; k >= 0; k--) { + let current = map[k] if (!current.length) { continue } diff --git a/remix-lib/src/storage.js b/remix-lib/src/storage.js index 305c8cf9e0..70fd28b5be 100644 --- a/remix-lib/src/storage.js +++ b/remix-lib/src/storage.js @@ -34,7 +34,7 @@ function Storage (prefix) { } this.rename = function (originalName, newName) { - var content = this.get(originalName) + const content = this.get(originalName) if (!this.set(newName, content)) { return false } diff --git a/remix-lib/src/trace/traceAnalyser.js b/remix-lib/src/trace/traceAnalyser.js index 33aa7c73f7..efdd5de49a 100644 --- a/remix-lib/src/trace/traceAnalyser.js +++ b/remix-lib/src/trace/traceAnalyser.js @@ -1,5 +1,5 @@ 'use strict' -var traceHelper = require('../helpers/traceHelper') +const traceHelper = require('../helpers/traceHelper') function TraceAnalyser (_cache) { this.traceCache = _cache @@ -9,19 +9,19 @@ function TraceAnalyser (_cache) { TraceAnalyser.prototype.analyse = function (trace, tx, callback) { this.trace = trace this.traceCache.pushStoreChanges(0, tx.to) - var context = { + let context = { storageContext: [tx.to], currentCallIndex: 0, lastCallIndex: 0 } - var callStack = [tx.to] + const callStack = [tx.to] this.traceCache.pushCall(trace[0], 0, callStack[0], callStack.slice(0)) if (traceHelper.isContractCreation(tx.to)) { this.traceCache.pushContractCreation(tx.to, tx.input) } this.buildCalldata(0, this.trace[0], tx, true) - for (var k = 0; k < this.trace.length; k++) { - var step = this.trace[k] + for (let k = 0; k < this.trace.length; k++) { + const step = this.trace[k] this.buildMemory(k, step) context = this.buildDepth(k, step, tx, callStack, context) context = this.buildStorage(k, step, context) @@ -32,27 +32,27 @@ TraceAnalyser.prototype.analyse = function (trace, tx, callback) { TraceAnalyser.prototype.buildReturnValues = function (index, step) { if (traceHelper.isReturnInstruction(step)) { - var offset = 2 * parseInt(step.stack[step.stack.length - 1], 16) - var size = 2 * parseInt(step.stack[step.stack.length - 2], 16) - var memory = this.trace[this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]].memory + const offset = 2 * parseInt(step.stack[step.stack.length - 1], 16) + const size = 2 * parseInt(step.stack[step.stack.length - 2], 16) + const memory = this.trace[this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]].memory this.traceCache.pushReturnValue(index, '0x' + memory.join('').substr(offset, size)) } } TraceAnalyser.prototype.buildCalldata = function (index, step, tx, newContext) { - var calldata = '' + let calldata = '' if (index === 0) { calldata = tx.input this.traceCache.pushCallDataChanges(index, calldata) } else if (!newContext) { - var lastCall = this.traceCache.callsData[this.traceCache.callDataChanges[this.traceCache.callDataChanges.length - 2]] + const lastCall = this.traceCache.callsData[this.traceCache.callDataChanges[this.traceCache.callDataChanges.length - 2]] this.traceCache.pushCallDataChanges(index + 1, lastCall) } else { - var memory = this.trace[this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]].memory - var callStep = this.trace[index] - var stack = callStep.stack - var offset = '' - var size = '' + const memory = this.trace[this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1]].memory + const callStep = this.trace[index] + const stack = callStep.stack + let offset = '' + let size = '' if (callStep.op === 'DELEGATECALL') { offset = 2 * parseInt(stack[stack.length - 3], 16) size = 2 * parseInt(stack[stack.length - 4], 16) @@ -73,7 +73,7 @@ TraceAnalyser.prototype.buildMemory = function (index, step) { TraceAnalyser.prototype.buildStorage = function (index, step, context) { if (traceHelper.newContextStorage(step) && !traceHelper.isCallToPrecompiledContract(index, this.trace)) { - var calledAddress = traceHelper.resolveCalledAddress(index, this.trace) + const calledAddress = traceHelper.resolveCalledAddress(index, this.trace) if (calledAddress) { context.storageContext.push(calledAddress) } else { @@ -94,11 +94,11 @@ TraceAnalyser.prototype.buildStorage = function (index, step, context) { TraceAnalyser.prototype.buildDepth = function (index, step, tx, callStack, context) { if (traceHelper.isCallInstruction(step) && !traceHelper.isCallToPrecompiledContract(index, this.trace)) { - var newAddress + let newAddress if (traceHelper.isCreateInstruction(step)) { newAddress = traceHelper.contractCreationToken(index) callStack.push(newAddress) - var lastMemoryChange = this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1] + const lastMemoryChange = this.traceCache.memoryChanges[this.traceCache.memoryChanges.length - 1] this.traceCache.pushContractCreationFromMemory(index, newAddress, this.trace, lastMemoryChange) } else { newAddress = traceHelper.resolveCalledAddress(index, this.trace) diff --git a/remix-lib/src/trace/traceCache.js b/remix-lib/src/trace/traceCache.js index 6cfe28d58f..0885cdb974 100644 --- a/remix-lib/src/trace/traceCache.js +++ b/remix-lib/src/trace/traceCache.js @@ -1,5 +1,5 @@ 'use strict' -var helper = require('../util') +const helper = require('../util') function TraceCache () { this.init() @@ -38,7 +38,7 @@ TraceCache.prototype.pushMemoryChanges = function (value) { // outOfGas has been removed because gas left logging is apparently made differently // in the vm/geth/eth. TODO add the error property (with about the error in all clients) TraceCache.prototype.pushCall = function (step, index, address, callStack, reverted) { - var validReturnStep = step.op === 'RETURN' || step.op === 'STOP' + let validReturnStep = step.op === 'RETURN' || step.op === 'STOP' if (validReturnStep || reverted) { if (this.currentCall) { this.currentCall.call.return = index - 1 @@ -49,7 +49,7 @@ TraceCache.prototype.pushCall = function (step, index, address, callStack, rever this.currentCall = parent ? { call: parent.call, parent: parent.parent } : null } } else { - var call = { + let call = { op: step.op, address: address, callStack: callStack, @@ -71,10 +71,10 @@ TraceCache.prototype.pushReturnValue = function (step, value) { } TraceCache.prototype.pushContractCreationFromMemory = function (index, token, trace, lastMemoryChange) { - var memory = trace[lastMemoryChange].memory - var stack = trace[index].stack - var offset = 2 * parseInt(stack[stack.length - 2], 16) - var size = 2 * parseInt(stack[stack.length - 3], 16) + const memory = trace[lastMemoryChange].memory + const stack = trace[index].stack + const offset = 2 * parseInt(stack[stack.length - 2], 16) + const size = 2 * parseInt(stack[stack.length - 3], 16) this.contractCreation[token] = '0x' + memory.join('').substr(offset, size) } @@ -98,9 +98,9 @@ TraceCache.prototype.pushStoreChanges = function (index, address, key, value) { } TraceCache.prototype.accumulateStorageChanges = function (index, address, storage) { - var ret = Object.assign({}, storage) + const ret = Object.assign({}, storage) for (var k in this.storageChanges) { - var changesIndex = this.storageChanges[k] + const changesIndex = this.storageChanges[k] if (changesIndex > index) { return ret } diff --git a/remix-lib/src/trace/traceManager.js b/remix-lib/src/trace/traceManager.js index c0c6d31379..ddd108cd2d 100644 --- a/remix-lib/src/trace/traceManager.js +++ b/remix-lib/src/trace/traceManager.js @@ -1,11 +1,11 @@ 'use strict' -var TraceAnalyser = require('./traceAnalyser') -var TraceRetriever = require('./traceRetriever') -var TraceCache = require('./traceCache') -var TraceStepManager = require('./traceStepManager') +const TraceAnalyser = require('./traceAnalyser') +const TraceRetriever = require('./traceRetriever') +const TraceCache = require('./traceCache') +const TraceStepManager = require('./traceStepManager') -var traceHelper = require('../helpers/traceHelper') -var util = require('../util') +const traceHelper = require('../helpers/traceHelper') +const util = require('../util') function TraceManager (options) { this.web3 = options.web3 @@ -25,7 +25,7 @@ TraceManager.prototype.resolveTrace = function (tx, callback) { if (!this.web3) callback('web3 not loaded', false) this.isLoading = true var self = this - this.traceRetriever.getTrace(tx.hash, function (error, result) { + this.traceRetriever.getTrace(tx.hash, (error, result) => { if (error) { console.log(error) self.isLoading = false @@ -76,7 +76,7 @@ TraceManager.prototype.getLength = function (callback) { } TraceManager.prototype.accumulateStorageChanges = function (index, address, storageOrigin, callback) { - var storage = this.traceCache.accumulateStorageChanges(index, address, storageOrigin) + const storage = this.traceCache.accumulateStorageChanges(index, address, storageOrigin) callback(null, storage) } @@ -85,41 +85,41 @@ TraceManager.prototype.getAddresses = function (callback) { } TraceManager.prototype.getCallDataAt = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } - var callDataChange = util.findLowerBoundValue(stepIndex, this.traceCache.callDataChanges) + const callDataChange = util.findLowerBoundValue(stepIndex, this.traceCache.callDataChanges) if (callDataChange === null) return callback('no calldata found', null) callback(null, [this.traceCache.callsData[callDataChange]]) } TraceManager.prototype.buildCallPath = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } - var callsPath = util.buildCallPath(stepIndex, this.traceCache.callsTree.call) + const callsPath = util.buildCallPath(stepIndex, this.traceCache.callsTree.call) if (callsPath === null) return callback('no call path built', null) callback(null, callsPath) } TraceManager.prototype.getCallStackAt = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } - var call = util.findCall(stepIndex, this.traceCache.callsTree.call) + const call = util.findCall(stepIndex, this.traceCache.callsTree.call) if (call === null) return callback('no callstack found', null) callback(null, call.callStack) } TraceManager.prototype.getStackAt = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } - var stack + let stack if (this.trace[stepIndex] && this.trace[stepIndex].stack) { // there's always a stack stack = this.trace[stepIndex].stack.slice(0) stack.reverse() @@ -130,11 +130,11 @@ TraceManager.prototype.getStackAt = function (stepIndex, callback) { } TraceManager.prototype.getLastCallChangeSince = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } - var callChange = util.findCall(stepIndex, this.traceCache.callsTree.call) + const callChange = util.findCall(stepIndex, this.traceCache.callsTree.call) if (callChange === null) { callback(null, 0) } else { @@ -143,7 +143,7 @@ TraceManager.prototype.getLastCallChangeSince = function (stepIndex, callback) { } TraceManager.prototype.getCurrentCalledAddressAt = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } @@ -169,17 +169,17 @@ TraceManager.prototype.getContractCreationCode = function (token, callback) { } TraceManager.prototype.getMemoryAt = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } - var lastChanges = util.findLowerBoundValue(stepIndex, this.traceCache.memoryChanges) + const lastChanges = util.findLowerBoundValue(stepIndex, this.traceCache.memoryChanges) if (lastChanges === null) return callback('no memory found', null) callback(null, this.trace[lastChanges].memory) } TraceManager.prototype.getCurrentPC = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } @@ -187,7 +187,7 @@ TraceManager.prototype.getCurrentPC = function (stepIndex, callback) { } TraceManager.prototype.getReturnValue = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } @@ -199,7 +199,7 @@ TraceManager.prototype.getReturnValue = function (stepIndex, callback) { } TraceManager.prototype.getCurrentStep = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } @@ -207,7 +207,7 @@ TraceManager.prototype.getCurrentStep = function (stepIndex, callback) { } TraceManager.prototype.getMemExpand = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } @@ -215,7 +215,7 @@ TraceManager.prototype.getMemExpand = function (stepIndex, callback) { } TraceManager.prototype.getStepCost = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } @@ -223,7 +223,7 @@ TraceManager.prototype.getStepCost = function (stepIndex, callback) { } TraceManager.prototype.getRemainingGas = function (stepIndex, callback) { - var check = this.checkRequestedStep(stepIndex) + const check = this.checkRequestedStep(stepIndex) if (check) { return callback(check, null) } @@ -262,8 +262,8 @@ TraceManager.prototype.checkRequestedStep = function (stepIndex) { } TraceManager.prototype.waterfall = function (calls, stepindex, cb) { - var ret = [] - var retError = null + let ret = [] + let retError = null for (var call in calls) { calls[call].apply(this, [stepindex, function (error, result) { retError = error diff --git a/remix-lib/src/trace/traceRetriever.js b/remix-lib/src/trace/traceRetriever.js index 07e757c0f0..4d3b78a697 100644 --- a/remix-lib/src/trace/traceRetriever.js +++ b/remix-lib/src/trace/traceRetriever.js @@ -5,7 +5,7 @@ function TraceRetriever (options) { } TraceRetriever.prototype.getTrace = function (txHash, callback) { - var options = { + const options = { disableStorage: true, disableMemory: false, disableStack: false, diff --git a/remix-lib/src/trace/traceStepManager.js b/remix-lib/src/trace/traceStepManager.js index e402224ec5..4cfbb67022 100644 --- a/remix-lib/src/trace/traceStepManager.js +++ b/remix-lib/src/trace/traceStepManager.js @@ -1,25 +1,25 @@ 'use strict' -var traceHelper = require('../helpers/traceHelper') -var util = require('../util') +const traceHelper = require('../helpers/traceHelper') +const util = require('../util') function TraceStepManager (_traceAnalyser) { this.traceAnalyser = _traceAnalyser } TraceStepManager.prototype.isCallInstruction = function (index) { - var state = this.traceAnalyser.trace[index] + const state = this.traceAnalyser.trace[index] return traceHelper.isCallInstruction(state) && !traceHelper.isCallToPrecompiledContract(index, this.traceAnalyser.trace) } TraceStepManager.prototype.isReturnInstruction = function (index) { - var state = this.traceAnalyser.trace[index] + const state = this.traceAnalyser.trace[index] return traceHelper.isReturnInstruction(state) } TraceStepManager.prototype.findStepOverBack = function (currentStep) { if (this.isReturnInstruction(currentStep)) { - var call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call) + const call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call) return call.start > 0 ? call.start - 1 : 0 } else { return currentStep > 0 ? currentStep - 1 : 0 @@ -28,7 +28,7 @@ TraceStepManager.prototype.findStepOverBack = function (currentStep) { TraceStepManager.prototype.findStepOverForward = function (currentStep) { if (this.isCallInstruction(currentStep)) { - var call = util.findCall(currentStep + 1, this.traceAnalyser.traceCache.callsTree.call) + const call = util.findCall(currentStep + 1, this.traceAnalyser.traceCache.callsTree.call) return call.return + 1 < this.traceAnalyser.trace.length ? call.return + 1 : this.traceAnalyser.trace.length - 1 } else { return this.traceAnalyser.trace.length >= currentStep + 1 ? currentStep + 1 : currentStep @@ -36,8 +36,8 @@ TraceStepManager.prototype.findStepOverForward = function (currentStep) { } TraceStepManager.prototype.findNextCall = function (currentStep) { - var call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call) - var subCalls = Object.keys(call.calls) + const call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call) + const subCalls = Object.keys(call.calls) if (subCalls.length) { var callStart = util.findLowerBound(currentStep, subCalls) + 1 if (subCalls.length > callStart) { @@ -51,7 +51,7 @@ TraceStepManager.prototype.findNextCall = function (currentStep) { } TraceStepManager.prototype.findStepOut = function (currentStep) { - var call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call) + const call = util.findCall(currentStep, this.traceAnalyser.traceCache.callsTree.call) return call.return } diff --git a/remix-lib/src/util.js b/remix-lib/src/util.js index 4bb0396119..2bfadca12b 100644 --- a/remix-lib/src/util.js +++ b/remix-lib/src/util.js @@ -1,5 +1,5 @@ 'use strict' -var ethutil = require('ethereumjs-util') +const ethutil = require('ethereumjs-util') /* contains misc util: @TODO should be splitted @@ -15,9 +15,9 @@ module.exports = { ints: IntArray */ hexConvert: function (ints) { - var ret = '0x' - for (var i = 0; i < ints.length; i++) { - var h = ints[i] + let ret = '0x' + for (let i = 0; i < ints.length; i++) { + const h = ints[i] if (h) { ret += (h <= 0xf ? '0' : '') + h.toString(16) } else { @@ -34,8 +34,8 @@ module.exports = { if (hexString.slice(0, 2) === '0x') { hexString = hexString.slice(2) } - var integers = [] - for (var i = 0; i < hexString.length; i += 2) { + const integers = [] + for (let i = 0; i < hexString.length; i += 2) { integers.push(parseInt(hexString.slice(i, i + 2), 16)) } return integers @@ -45,9 +45,9 @@ module.exports = { ints: list of BNs */ hexListFromBNs: function (bnList) { - var ret = [] - for (var k in bnList) { - var v = bnList[k] + const ret = [] + for (let k in bnList) { + const v = bnList[k] if (ethutil.BN.isBN(v)) { ret.push('0x' + v.toString('hex', 64)) } else { @@ -61,8 +61,8 @@ module.exports = { ints: list of IntArrays */ hexListConvert: function (intsList) { - var ret = [] - for (var k in intsList) { + const ret = [] + for (let k in intsList) { ret.push(this.hexConvert(intsList[k])) } return ret @@ -72,10 +72,10 @@ module.exports = { ints: ints: IntArray */ formatMemory: function (mem) { - var hexMem = this.hexConvert(mem).substr(2) - var ret = [] - for (var k = 0; k < hexMem.length; k += 32) { - var row = hexMem.substr(k, 32) + const hexMem = this.hexConvert(mem).substr(2) + const ret = [] + for (let k = 0; k < hexMem.length; k += 32) { + const row = hexMem.substr(k, 32) ret.push(row) } return ret @@ -87,11 +87,11 @@ module.exports = { return largest i such that array[i] <= target; return -1 if array[0] > target || array is empty */ findLowerBound: function (target, array) { - var start = 0 - var length = array.length + let start = 0 + let length = array.length while (length > 0) { - var half = length >> 1 - var middle = start + half + const half = length >> 1 + const middle = start + half if (array[middle] <= target) { length = length - 1 - half start = middle + 1 @@ -108,7 +108,7 @@ module.exports = { return largest array[i] such that array[i] <= target; return null if array[0] > target || array is empty */ findLowerBoundValue: function (target, array) { - var index = this.findLowerBound(target, array) + const index = this.findLowerBound(target, array) return index >= 0 ? array[index] : null }, @@ -122,13 +122,13 @@ module.exports = { if (array.length === 0) { return -1 } - var index = this.findLowerBound(target, array) + const index = this.findLowerBound(target, array) if (index < 0) { return 0 } else if (index >= array.length - 1) { return array.length - 1 } else { - var middle = (array[index] + array[index + 1]) / 2 + const middle = (array[index] + array[index + 1]) / 2 return target <= middle ? index : index + 1 } }, @@ -161,7 +161,7 @@ module.exports = { if (typeof value === 'string' && value.indexOf('0x') !== 0) { value = '0x' + value } - var ret = ethutil.bufferToHex(ethutil.setLengthLeft(value, 32)) + let ret = ethutil.bufferToHex(ethutil.setLengthLeft(value, 32)) ret = ethutil.keccak(ret) return ethutil.bufferToHex(ret) }, @@ -218,7 +218,7 @@ module.exports = { // if code2 is not a library, well we still suppose that the comparison remain relevant even if we remove some information from `code1` code1 = replaceLibReference(code1, 4) } - var pos = -1 + let pos = -1 while ((pos = code2.search(/__(.*)__/)) !== -1) { code2 = replaceLibReference(code2, pos) code1 = replaceLibReference(code1, pos) @@ -240,22 +240,22 @@ function replaceLibReference (code, pos) { } function buildCallPath (index, rootCall) { - var ret = [] + const ret = [] findCallInternal(index, rootCall, ret) return ret } function findCall (index, rootCall) { - var ret = buildCallPath(index, rootCall) + const ret = buildCallPath(index, rootCall) return ret[ret.length - 1] } function findCallInternal (index, rootCall, callsPath) { - var calls = Object.keys(rootCall.calls) - var ret = rootCall + const calls = Object.keys(rootCall.calls) + const ret = rootCall callsPath.push(rootCall) - for (var k in calls) { - var subCall = rootCall.calls[calls[k]] + for (let k in calls) { + let subCall = rootCall.calls[calls[k]] if (index >= subCall.start && index <= subCall.return) { findCallInternal(index, subCall, callsPath) break @@ -268,7 +268,7 @@ function findCallInternal (index, rootCall, callsPath) { function groupBy (arr, key) { return arr.reduce((sum, item) => { const groupByVal = item[key] - var groupedItems = sum[groupByVal] || [] + const groupedItems = sum[groupByVal] || [] groupedItems.push(item) sum[groupByVal] = groupedItems return sum diff --git a/remix-lib/src/web3Provider/dummyProvider.js b/remix-lib/src/web3Provider/dummyProvider.js index 03ba85fdf7..122601f880 100644 --- a/remix-lib/src/web3Provider/dummyProvider.js +++ b/remix-lib/src/web3Provider/dummyProvider.js @@ -1,13 +1,12 @@ function dummyProvider () { - var self = this this.eth = {} this.debug = {} - this.eth.getCode = function (address, cb) { return self.getCode(address, cb) } - this.eth.getTransaction = function (hash, cb) { return self.getTransaction(hash, cb) } - this.eth.getTransactionFromBlock = function (blockNumber, txIndex, cb) { return self.getTransactionFromBlock(blockNumber, txIndex, cb) } - this.eth.getBlockNumber = function (cb) { return self.getBlockNumber(cb) } - this.debug.traceTransaction = function (hash, options, cb) { return self.traceTransaction(hash, options, cb) } - this.debug.storageRangeAt = function (blockNumber, txIndex, address, start, end, maxLength, cb) { return self.storageRangeAt(blockNumber, txIndex, address, start, end, maxLength, cb) } + this.eth.getCode = (address, cb) => { return this.getCode(address, cb) } + this.eth.getTransaction = (hash, cb) => { return this.getTransaction(hash, cb) } + this.eth.getTransactionFromBlock = (blockNumber, txIndex, cb) => { return this.getTransactionFromBlock(blockNumber, txIndex, cb) } + this.eth.getBlockNumber = (cb) => { return this.getBlockNumber(cb) } + this.debug.traceTransaction = (hash, options, cb) => { return this.traceTransaction(hash, options, cb) } + this.debug.storageRangeAt = (blockNumber, txIndex, address, start, end, maxLength, cb) => { return this.storageRangeAt(blockNumber, txIndex, address, start, end, maxLength, cb) } this.providers = { 'HttpProvider': function (url) {} } this.currentProvider = {'host': ''} } diff --git a/remix-lib/src/web3Provider/web3Providers.js b/remix-lib/src/web3Provider/web3Providers.js index ad53b8b2e6..4b746c4c70 100644 --- a/remix-lib/src/web3Provider/web3Providers.js +++ b/remix-lib/src/web3Provider/web3Providers.js @@ -1,5 +1,5 @@ -var Web3VMProvider = require('./web3VmProvider') -var init = require('../init') +const Web3VMProvider = require('./web3VmProvider') +const init = require('../init') function Web3Providers () { this.modes = {} @@ -7,7 +7,7 @@ function Web3Providers () { Web3Providers.prototype.addProvider = function (type, obj) { if (type === 'INTERNAL') { - var web3 = init.loadWeb3() + const web3 = init.loadWeb3() this.addWeb3(type, web3) } else if (type === 'vm') { this.addVM(type, obj) @@ -30,7 +30,7 @@ Web3Providers.prototype.addWeb3 = function (type, web3) { } Web3Providers.prototype.addVM = function (type, vm) { - var vmProvider = new Web3VMProvider() + const vmProvider = new Web3VMProvider() vmProvider.setVM(vm) this.modes[type] = vmProvider } diff --git a/remix-lib/src/web3Provider/web3VmProvider.js b/remix-lib/src/web3Provider/web3VmProvider.js index 42ace40c0d..f65a342bba 100644 --- a/remix-lib/src/web3Provider/web3VmProvider.js +++ b/remix-lib/src/web3Provider/web3VmProvider.js @@ -1,11 +1,10 @@ -var util = require('../util') -var uiutil = require('../helpers/uiHelper') -var traceHelper = require('../helpers/traceHelper') -var ethutil = require('ethereumjs-util') -var Web3 = require('web3') +const util = require('../util') +const uiutil = require('../helpers/uiHelper') +const traceHelper = require('../helpers/traceHelper') +const ethutil = require('ethereumjs-util') +const Web3 = require('web3') function web3VmProvider () { - var self = this this.web3 = new Web3() this.vm this.vmTraces = {} @@ -18,40 +17,48 @@ function web3VmProvider () { this.incr = 0 this.eth = {} this.debug = {} - this.eth.getCode = (...args) => self.getCode(...args) - this.eth.getTransaction = (...args) => self.getTransaction(...args) - this.eth.getTransactionReceipt = (...args) => self.getTransactionReceipt(...args) - this.eth.getTransactionFromBlock = (...args) => self.getTransactionFromBlock(...args) - this.eth.getBlockNumber = (...args) => self.getBlockNumber(...args) - this.debug.traceTransaction = (...args) => self.traceTransaction(...args) - this.debug.storageRangeAt = (...args) => self.storageRangeAt(...args) - this.debug.preimage = (...args) => self.preimage(...args) + this.eth.getCode = (...args) => this.getCode(...args) + this.eth.getTransaction = (...args) => this.getTransaction(...args) + this.eth.getTransactionReceipt = (...args) => this.getTransactionReceipt(...args) + this.eth.getTransactionFromBlock = (...args) => this.getTransactionFromBlock(...args) + this.eth.getBlockNumber = (...args) => this.getBlockNumber(...args) + this.debug.traceTransaction = (...args) => this.traceTransaction(...args) + this.debug.storageRangeAt = (...args) => this.storageRangeAt(...args) + this.debug.preimage = (...args) => this.preimage(...args) this.providers = { 'HttpProvider': function (url) {} } this.currentProvider = {'host': 'vm provider'} this.storageCache = {} this.lastProcessedStorageTxHash = {} this.sha3Preimages = {} // util + this.sha3 = (...args) => this.web3.utils.sha3(...args) + this.toHex = (...args) => this.web3.utils.toHex(...args) + this.toAscii = (...args) => this.web3.utils.hexToAscii(...args) + this.fromAscii = (...args) => this.web3.utils.asciiToHex(...args) + this.fromDecimal = (...args) => this.web3.utils.numberToHex(...args) + this.fromWei = (...args) => this.web3.utils.fromWei(...args) + this.toWei = (...args) => this.web3.utils.toWei(...args) + this.toBigNumber = (...args) => this.web3.utils.toBN(...args) + this.isAddress = (...args) => this.web3.utils.isAddress(...args) this.utils = Web3.utils || [] } web3VmProvider.prototype.setVM = function (vm) { if (this.vm === vm) return - var self = this this.vm = vm - this.vm.on('step', function (data) { - self.pushTrace(self, data) + this.vm.on('step', (data) => { + this.pushTrace(this, data) }) - this.vm.on('afterTx', function (data) { - self.txProcessed(self, data) + this.vm.on('afterTx', (data) => { + this.txProcessed(this, data) }) - this.vm.on('beforeTx', function (data) { - self.txWillProcess(self, data) + this.vm.on('beforeTx', (data) => { + this.txWillProcess(this, data) }) } web3VmProvider.prototype.releaseCurrentHash = function () { - var ret = this.processingHash + const ret = this.processingHash this.processingHash = undefined return ret } @@ -64,7 +71,7 @@ web3VmProvider.prototype.txWillProcess = function (self, data) { return: '0x0', structLogs: [] } - var tx = {} + let tx = {} tx.hash = self.processingHash tx.from = util.hexConvert(data.getSenderAddress()) if (data.to && data.to.length) { @@ -82,7 +89,7 @@ web3VmProvider.prototype.txWillProcess = function (self, data) { self.storageCache[self.processingHash] = {} if (tx.to) { const account = ethutil.toBuffer(tx.to) - self.vm.stateManager.dumpStorage(account, function (storage) { + self.vm.stateManager.dumpStorage(account, (storage) => { self.storageCache[self.processingHash][tx.to] = storage self.lastProcessedStorageTxHash[tx.to] = self.processingHash }) @@ -91,16 +98,16 @@ web3VmProvider.prototype.txWillProcess = function (self, data) { } web3VmProvider.prototype.txProcessed = function (self, data) { - var lastOp = self.vmTraces[self.processingHash].structLogs[self.processingIndex - 1] + const lastOp = self.vmTraces[self.processingHash].structLogs[self.processingIndex - 1] if (lastOp) { lastOp.error = lastOp.op !== 'RETURN' && lastOp.op !== 'STOP' && lastOp.op !== 'SELFDESTRUCT' } self.vmTraces[self.processingHash].gas = '0x' + data.gasUsed.toString(16) - var logs = [] - for (var l in data.execResult.logs) { - var log = data.execResult.logs[l] - var topics = [] + const logs = [] + for (let l in data.execResult.logs) { + const log = data.execResult.logs[l] + const topics = [] if (log[1].length > 0) { for (var k in log[1]) { topics.push('0x' + log[1][k].toString('hex')) @@ -121,7 +128,7 @@ web3VmProvider.prototype.txProcessed = function (self, data) { self.txsReceipt[self.processingHash].status = `0x${status}` if (data.createdAddress) { - var address = util.hexConvert(data.createdAddress) + const address = util.hexConvert(data.createdAddress) self.vmTraces[self.processingHash].return = address self.txsReceipt[self.processingHash].contractAddress = address } else if (data.execResult.returnValue) { @@ -135,12 +142,12 @@ web3VmProvider.prototype.txProcessed = function (self, data) { } web3VmProvider.prototype.pushTrace = function (self, data) { - var depth = data.depth + 1 // geth starts the depth from 1 + const depth = data.depth + 1 // geth starts the depth from 1 if (!self.processingHash) { console.log('no tx processing') return } - var previousopcode + let previousopcode if (self.vmTraces[self.processingHash] && self.vmTraces[self.processingHash].structLogs[this.processingIndex - 1]) { previousopcode = self.vmTraces[self.processingHash].structLogs[this.processingIndex - 1] } @@ -149,7 +156,7 @@ web3VmProvider.prototype.pushTrace = function (self, data) { // returning from context, set error it is not STOP, RETURN previousopcode.invalidDepthChange = previousopcode.op !== 'RETURN' && previousopcode.op !== 'STOP' } - var step = { + const step = { stack: util.hexListFromBNs(data.stack), memory: util.formatMemory(data.memory), storage: data.storage, @@ -178,8 +185,8 @@ web3VmProvider.prototype.pushTrace = function (self, data) { } } if (previousopcode && traceHelper.isSHA3Instruction(previousopcode)) { - var preimage = getSha3Input(previousopcode.stack, previousopcode.memory) - var imageHash = step.stack[step.stack.length - 1].replace('0x', '') + const preimage = getSha3Input(previousopcode.stack, previousopcode.memory) + const imageHash = step.stack[step.stack.length - 1].replace('0x', '') self.sha3Preimages[imageHash] = { 'preimage': preimage } @@ -191,7 +198,7 @@ web3VmProvider.prototype.pushTrace = function (self, data) { web3VmProvider.prototype.getCode = function (address, cb) { const account = ethutil.toBuffer(address) - this.vm.stateManager.getContractCode(account, function (error, result) { + this.vm.stateManager.getContractCode(account, (error, result) => { cb(error, util.hexConvert(result)) }) } @@ -219,7 +226,7 @@ web3VmProvider.prototype.storageRangeAt = function (blockNumber, txIndex, addres } if (this.storageCache[txIndex] && this.storageCache[txIndex][address]) { - var storage = this.storageCache[txIndex][address] + const storage = this.storageCache[txIndex][address] return cb(null, { storage: JSON.parse(JSON.stringify(storage)), nextKey: null @@ -259,7 +266,7 @@ web3VmProvider.prototype.getTransactionReceipt = function (txHash, cb) { } web3VmProvider.prototype.getTransactionFromBlock = function (blockNumber, txIndex, cb) { - var mes = 'not supposed to be needed by remix in vmmode' + const mes = 'not supposed to be needed by remix in vmmode' console.log(mes) if (cb) { cb(mes, null) @@ -272,26 +279,26 @@ web3VmProvider.prototype.preimage = function (hashedKey, cb) { } function getSha3Input (stack, memory) { - var memoryStart = stack[stack.length - 1] - var memoryLength = stack[stack.length - 2] - var memStartDec = (new ethutil.BN(memoryStart.replace('0x', ''), 16)).toString(10) + let memoryStart = stack[stack.length - 1] + let memoryLength = stack[stack.length - 2] + const memStartDec = (new ethutil.BN(memoryStart.replace('0x', ''), 16)).toString(10) memoryStart = parseInt(memStartDec) * 2 - var memLengthDec = (new ethutil.BN(memoryLength.replace('0x', ''), 16).toString(10)) + const memLengthDec = (new ethutil.BN(memoryLength.replace('0x', ''), 16).toString(10)) memoryLength = parseInt(memLengthDec) * 2 - var i = Math.floor(memoryStart / 32) - var maxIndex = Math.floor(memoryLength / 32) + i + let i = Math.floor(memoryStart / 32) + const maxIndex = Math.floor(memoryLength / 32) + i if (!memory[i]) { return emptyFill(memoryLength) } - var sha3Input = memory[i].slice(memoryStart - 32 * i) + let sha3Input = memory[i].slice(memoryStart - 32 * i) i++ while (i < maxIndex) { sha3Input += memory[i] ? memory[i] : emptyFill(32) i++ } if (sha3Input.length < memoryLength) { - var leftSize = memoryLength - sha3Input.length + const leftSize = memoryLength - sha3Input.length sha3Input += memory[i] ? memory[i].slice(0, leftSize) : emptyFill(leftSize) } return sha3Input diff --git a/remix-lib/test/astwalker.js b/remix-lib/test/astwalker.js index 1191001333..e91bbe798c 100644 --- a/remix-lib/test/astwalker.js +++ b/remix-lib/test/astwalker.js @@ -1,12 +1,12 @@ 'use strict' -var tape = require('tape') -var AstWalker = require('../src/astWalker') -var node = require('./resources/ast') +const tape = require('tape') +const AstWalker = require('../src/astWalker') +const node = require('./resources/ast') tape('ASTWalker', function (t) { t.test('ASTWalker.walk', function (st) { st.plan(24) - var astwalker = new AstWalker() + const astwalker = new AstWalker() astwalker.walk(node.ast.legacyAST, function (node) { if (node.name === 'ContractDefinition') { @@ -18,7 +18,7 @@ tape('ASTWalker', function (t) { return true }) - var callback = {} + const callback = {} callback.FunctionDefinition = function (node) { st.equal(node.name, 'FunctionDefinition') st.equal(node.attributes.name === 'set' || node.attributes.name === 'get', true) diff --git a/remix-lib/test/codeManager.js b/remix-lib/test/codeManager.js index 09db112d0f..52f0ea3768 100644 --- a/remix-lib/test/codeManager.js +++ b/remix-lib/test/codeManager.js @@ -1,28 +1,28 @@ 'use strict' -var tape = require('tape') -var Web3Providers = require('../src/web3Provider/web3Providers') -var TraceManager = require('../src/trace/traceManager') -var CodeManager = require('../src/code/codeManager') -var web3Test = require('./resources/testWeb3') +const tape = require('tape') +const Web3Providers = require('../src/web3Provider/web3Providers') +const TraceManager = require('../src/trace/traceManager') +const CodeManager = require('../src/code/codeManager') +const web3Test = require('./resources/testWeb3') let web3 = null tape('CodeManager', function (t) { - var codeManager - var web3Providers = new Web3Providers() + let codeManager + const web3Providers = new Web3Providers() web3Providers.addProvider('TEST', web3Test) web3Providers.get('TEST', function (error, obj) { if (error) { - var mes = 'provider TEST not defined' + const mes = 'provider TEST not defined' console.log(mes) t.fail(mes) } else { web3 = obj - var traceManager = new TraceManager({web3: web3}) + const traceManager = new TraceManager({web3: web3}) codeManager = new CodeManager(traceManager) - var contractCode = web3.eth.getCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5') + const contractCode = web3.eth.getCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5') codeManager.codeResolver.cacheExecutingCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', contractCode) // so a call to web3 is not necessary - var tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51') + const tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51') traceManager.resolveTrace(tx, function (error, result) { if (error) { t.fail(' - traceManager.resolveTrace - failed ' + result) @@ -63,7 +63,7 @@ function continueTesting (t, codeManager) { } } }) - var tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51') + const tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51') codeManager.resolveStep(0, tx) codeManager.resolveStep(70, tx) }) diff --git a/remix-lib/test/disassembler.js b/remix-lib/test/disassembler.js index d0c617f010..15f7a44fa3 100644 --- a/remix-lib/test/disassembler.js +++ b/remix-lib/test/disassembler.js @@ -1,7 +1,7 @@ 'use strict' -var tape = require('tape') -var disassemble = require('../src/code/disassembler').disassemble +const tape = require('tape') +const disassemble = require('../src/code/disassembler').disassemble tape('Disassembler', function (t) { t.test('empty', function (st) { @@ -18,8 +18,8 @@ tape('Disassembler', function (t) { }) t.test('complexcode', function (st) { st.plan(1) - var code = '60606040526009600060005055607e8060186000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480630dbe671f146039576035565b6002565b3460025760486004805050604a565b005b6000600090505b600a811015607a5760006000818150548092919060010191905055505b80806001019150506051565b5b5056' - var asm = `mstore(0x40, 0x60) + const code = '60606040526009600060005055607e8060186000396000f360606040526000357c0100000000000000000000000000000000000000000000000000000000900480630dbe671f146039576035565b6002565b3460025760486004805050604a565b005b6000600090505b600a811015607a5760006000818150548092919060010191905055505b80806001019150506051565b5b5056' + const asm = `mstore(0x40, 0x60) 0x09 0x00 pop(0x00) diff --git a/remix-lib/test/eventManager.js b/remix-lib/test/eventManager.js index 41ca659fe1..6ca027b486 100644 --- a/remix-lib/test/eventManager.js +++ b/remix-lib/test/eventManager.js @@ -1,16 +1,16 @@ 'use strict' -var tape = require('tape') -var EventManager = require('../src/eventManager') +const tape = require('tape') +const EventManager = require('../src/eventManager') tape('eventManager', function (t) { t.test('eventManager', function (st) { - var events = new EventManager() - var listenner = {} + const events = new EventManager() + const listenner = {} - var trace = '' + let trace = '' listenner.listen = function (data1) { trace += data1 } - var registeredFunction = function (data) { + const registeredFunction = function (data) { trace += data } events.register('event1', listenner, listenner.listen) diff --git a/remix-lib/test/init.js b/remix-lib/test/init.js index bd8f9114ea..51c1a5be08 100644 --- a/remix-lib/test/init.js +++ b/remix-lib/test/init.js @@ -9,7 +9,7 @@ var init = { }, readFile: function (filename, callback) { - var fs = require('fs') + const fs = require('fs') try { console.log('reading ' + filename) if (callback) { diff --git a/remix-lib/test/resources/ast.js b/remix-lib/test/resources/ast.js index 7fa15f2615..b8a4650b44 100644 --- a/remix-lib/test/resources/ast.js +++ b/remix-lib/test/resources/ast.js @@ -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"}} diff --git a/remix-lib/test/resources/sourceMapping.js b/remix-lib/test/resources/sourceMapping.js index f2f64a830e..af80384fe1 100644 --- a/remix-lib/test/resources/sourceMapping.js +++ b/remix-lib/test/resources/sourceMapping.js @@ -1,4 +1,4 @@ -var sourceRuntimeMapping = {} +const sourceRuntimeMapping = {} sourceRuntimeMapping.mapping = '0:205:4:-;;;;;;;;;;;;;;;;;;;;;;55:74;;;;;;;;;;;;;;;;;;;;;;;;;;142:61;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;55:74;103:2;99:1;;:6;;;;;120:2;116:1;;:6;;;;;55:74;;;:::o;142:61::-;166:6;174;142:61;;;:::o' sourceRuntimeMapping.source = `contract test { int x; diff --git a/remix-lib/test/resources/testWeb3.js b/remix-lib/test/resources/testWeb3.js index a138a81eb4..79224d5fc1 100644 --- a/remix-lib/test/resources/testWeb3.js +++ b/remix-lib/test/resources/testWeb3.js @@ -1,9 +1,9 @@ 'use strict' -var init = require('../init') -var web3Override = {} +const init = require('../init') +const web3Override = {} web3Override.eth = {} web3Override.debug = {} -var data = init.readFile(require('path').resolve(__dirname, 'testWeb3.json')) +let data = init.readFile(require('path').resolve(__dirname, 'testWeb3.json')) data = JSON.parse(data) web3Override.eth.getCode = function (address, callback) { diff --git a/remix-lib/test/sourceMappingDecoder.js b/remix-lib/test/sourceMappingDecoder.js index 5be0348132..fd09ce6eb7 100644 --- a/remix-lib/test/sourceMappingDecoder.js +++ b/remix-lib/test/sourceMappingDecoder.js @@ -1,16 +1,16 @@ 'use strict' -var tape = require('tape') -var sourceMapping = require('./resources/sourceMapping') -var SourceMappingDecoder = require('../src/sourceMappingDecoder') -var compiler = require('solc') -var compilerInput = require('../src/helpers/compilerHelper').compilerInput +const tape = require('tape') +const sourceMapping = require('./resources/sourceMapping') +const SourceMappingDecoder = require('../src/sourceMappingDecoder') +const compiler = require('solc') +const compilerInput = require('../src/helpers/compilerHelper').compilerInput tape('SourceMappingDecoder', function (t) { t.test('SourceMappingDecoder.findNodeAtInstructionIndex', function (st) { - var output = compiler.compile(compilerInput(contracts)) + let output = compiler.compile(compilerInput(contracts)) output = JSON.parse(output) - var sourceMappingDecoder = new SourceMappingDecoder() - var node = sourceMappingDecoder.findNodeAtInstructionIndex('FunctionDefinition', 2, output.contracts['test.sol']['test'].evm.deployedBytecode.sourceMap, output.sources['test.sol']) + const sourceMappingDecoder = new SourceMappingDecoder() + let node = sourceMappingDecoder.findNodeAtInstructionIndex('FunctionDefinition', 2, output.contracts['test.sol']['test'].evm.deployedBytecode.sourceMap, output.sources['test.sol']) st.equal(node, null) node = sourceMappingDecoder.findNodeAtInstructionIndex('FunctionDefinition', 80, output.contracts['test.sol']['test'].evm.deployedBytecode.sourceMap, output.sources['test.sol']) st.notEqual(node, null) @@ -20,12 +20,12 @@ tape('SourceMappingDecoder', function (t) { st.end() }) - var testSourceMapping = {} + const testSourceMapping = {} t.test('sourceMappingDecoder', function (st) { st.plan(28) - var sourceMappingDecoder = new SourceMappingDecoder() + const sourceMappingDecoder = new SourceMappingDecoder() console.log('test decompressAll') - var result = sourceMappingDecoder.decompressAll(sourceMapping.mapping) + let result = sourceMappingDecoder.decompressAll(sourceMapping.mapping) st.equal(result[0].start, 0) st.equal(result[0].length, 205) st.equal(result[0].file, 4) @@ -42,7 +42,7 @@ tape('SourceMappingDecoder', function (t) { st.equal(result[22].file, 4) st.equal(result[22].jump, '-') - var last = result.length - 1 + const last = result.length - 1 st.equal(result[last].start, 142) st.equal(result[last].length, 61) st.equal(result[last].file, 4) @@ -77,11 +77,11 @@ tape('SourceMappingDecoder', function (t) { t.test('sourceMappingLineColumnConverter', function (st) { st.plan(14) - var sourceMappingDecoder = new SourceMappingDecoder() - var linesbreak = sourceMappingDecoder.getLinebreakPositions(sourceMapping.source) + const sourceMappingDecoder = new SourceMappingDecoder() + const linesbreak = sourceMappingDecoder.getLinebreakPositions(sourceMapping.source) st.equal(linesbreak[0], 16) st.equal(linesbreak[5], 84) - var result = sourceMappingDecoder.convertOffsetToLineColumn(testSourceMapping[21], linesbreak) + let result = sourceMappingDecoder.convertOffsetToLineColumn(testSourceMapping[21], linesbreak) st.equal(result.start.line, 0) st.equal(result.start.column, 0) st.equal(result.end.line, 15) @@ -92,7 +92,7 @@ tape('SourceMappingDecoder', function (t) { st.equal(result.end.line, 7) st.equal(result.end.column, 14) - var res = { // point to \n + const res = { // point to \n start: 103, length: 4, file: 4, @@ -106,7 +106,7 @@ tape('SourceMappingDecoder', function (t) { }) }) -var contracts = `contract test { +const contracts = `contract test { function f1() public returns (uint) { uint t = 4; return t; diff --git a/remix-lib/test/traceManager.js b/remix-lib/test/traceManager.js index 5eb23f55b7..aa46414cf6 100644 --- a/remix-lib/test/traceManager.js +++ b/remix-lib/test/traceManager.js @@ -1,20 +1,20 @@ 'use strict' -var TraceManager = require('../src/trace/traceManager') -var tape = require('tape') -var Web3Providers = require('../src/web3Provider/web3Providers') -var web3Test = require('./resources/testWeb3') +const TraceManager = require('../src/trace/traceManager') +const tape = require('tape') +const Web3Providers = require('../src/web3Provider/web3Providers') +const web3Test = require('./resources/testWeb3') let web3 = null tape('TraceManager', function (t) { - var traceManager + let traceManager t.test('TraceManager.init', function (st) { - var web3Providers = new Web3Providers() + const web3Providers = new Web3Providers() web3Providers.addProvider('TEST', web3Test) web3Providers.get('TEST', function (error, obj) { if (error) { - var mes = 'provider TEST not defined' + const mes = 'provider TEST not defined' console.log(mes) st.fail(mes) } else { @@ -26,7 +26,7 @@ tape('TraceManager', function (t) { }) t.test('TraceManager.resolveTrace', function (st) { - var tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51') + const tx = web3.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51') traceManager.resolveTrace(tx, function (error, result) { if (error) { st.fail(' - traceManager.resolveTrace - failed ' + result) @@ -275,21 +275,21 @@ tape('TraceManager', function (t) { }) t.test('TraceManager.findStepOverBack', function (st) { - var result = traceManager.findStepOverBack(116) + const result = traceManager.findStepOverBack(116) console.log(result) st.ok(result === 115) st.end() }) t.test('TraceManager.findStepOverForward', function (st) { - var result = traceManager.findStepOverForward(66) + const result = traceManager.findStepOverForward(66) console.log(result) st.ok(result === 67) st.end() }) t.test('TraceManager.findNextCall', function (st) { - var result = traceManager.findNextCall(10) + const result = traceManager.findNextCall(10) console.log(result) st.ok(result === 63) st.end() diff --git a/remix-lib/test/txFormat.js b/remix-lib/test/txFormat.js index 0ce8b73a7d..a55b792ae3 100644 --- a/remix-lib/test/txFormat.js +++ b/remix-lib/test/txFormat.js @@ -1,12 +1,12 @@ 'use strict' -var tape = require('tape') -var txFormat = require('../src/execution/txFormat') -var txHelper = require('../src/execution/txHelper') -var util = require('../src/util') -var compiler = require('solc') -var compilerInput = require('../src/helpers/compilerHelper').compilerInput -var executionContext = require('../src/execution/execution-context') -var solidityVersion = 'v0.6.0+commit.26b70077' +const tape = require('tape') +const txFormat = require('../src/execution/txFormat') +const txHelper = require('../src/execution/txHelper') +const util = require('../src/util') +let compiler = require('solc') +const compilerInput = require('../src/helpers/compilerHelper').compilerInput +const executionContext = require('../src/execution/execution-context') +const solidityVersion = 'v0.6.0+commit.26b70077' /* tape *********************************************************** */ tape('load compiler ' + solidityVersion, function (t) { @@ -18,11 +18,11 @@ tape('load compiler ' + solidityVersion, function (t) { }) }) -var context +let context tape('ContractParameters - (TxFormat.buildData) - format input parameters', function (t) { - var output = compiler.compile(compilerInput(uintContract)) + let output = compiler.compile(compilerInput(uintContract)) output = JSON.parse(output) - var contract = output.contracts['test.sol']['uintContractTest'] + const contract = output.contracts['test.sol']['uintContractTest'] context = { output, contract } t.test('(TxFormat.buildData)', function (st) { @@ -48,9 +48,9 @@ function testWithInput (st, params, expected) { tape('ContractStringParameters - (TxFormat.buildData) - format string input parameters', function (t) { - var output = compiler.compile(compilerInput(stringContract)) + let output = compiler.compile(compilerInput(stringContract)) output = JSON.parse(output) - var contract = output.contracts['test.sol']['stringContractTest'] + const contract = output.contracts['test.sol']['stringContractTest'] context = { output, contract } t.test('(TxFormat.buildData)', function (st) { st.plan(3) @@ -74,9 +74,9 @@ function testWithStringInput (st, params, expected) { } tape('ContractArrayParameters - (TxFormat.buildData) - format array input parameters', function (t) { - var output = compiler.compile(compilerInput(arrayContract)) + let output = compiler.compile(compilerInput(arrayContract)) output = JSON.parse(output) - var contract = output.contracts['test.sol']['arrayContractTest'] + const contract = output.contracts['test.sol']['arrayContractTest'] context = { output, contract } t.test('(TxFormat.buildData)', function (st) { st.plan(3) @@ -100,9 +100,9 @@ function testWithArrayInput (st, params, expected) { } tape('ContractNestedArrayParameters - (TxFormat.buildData) - format nested array input parameters', function (t) { - var output = compiler.compile(compilerInput(nestedArrayContract)) + let output = compiler.compile(compilerInput(nestedArrayContract)) output = JSON.parse(output) - var contract = output.contracts['test.sol']['nestedArrayContractTest'] + let contract = output.contracts['test.sol']['nestedArrayContractTest'] context = { output, contract } t.test('(TxFormat.buildData)', function (st) { st.plan(2) @@ -129,14 +129,14 @@ function testWithNestedArrayInput (st, params, expected) { tape('ContractParameters - (TxFormat.buildData) - link Libraries', function (t) { executionContext.setContext('vm') - var compileData = compiler.compile(compilerInput(deploySimpleLib)) + const compileData = compiler.compile(compilerInput(deploySimpleLib)) - var fakeDeployedContracts = { + const fakeDeployedContracts = { lib1: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e11', lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e33', testContractLinkLibrary: '0xf7a10e525d4b168f45f74db1b61f63d3e7619e22' } - var callbackDeployLibraries = (param, callback) => { + const callbackDeployLibraries = (param, callback) => { callback(null, { result: { createdAddress: fakeDeployedContracts[param.data.contractName] @@ -146,29 +146,29 @@ tape('ContractParameters - (TxFormat.buildData) - link Libraries', function (t) t.test('(TxFormat.buildData and link library (standard way))', function (st) { st.plan(6) - var output = JSON.parse(compileData) - var contract = output.contracts['test.sol']['testContractLinkLibrary'] + const output = JSON.parse(compileData) + const contract = output.contracts['test.sol']['testContractLinkLibrary'] context = { output, contract } testLinkLibrary(st, fakeDeployedContracts, callbackDeployLibraries) }) t.test('(TxFormat.encodeConstructorCallAndLinkLibraries and link library (standard way))', function (st) { st.plan(12) - var output = JSON.parse(compileData) - var contract = output.contracts['test.sol']['testContractLinkLibrary'] + const output = JSON.parse(compileData) + const contract = output.contracts['test.sol']['testContractLinkLibrary'] context = { output, contract } testLinkLibrary2(st, callbackDeployLibraries) }) }) function testLinkLibrary (st, fakeDeployedContracts, callbackDeployLibraries) { - var deployMsg = ['creation of library test.sol:lib1 pending...', + const deployMsg = ['creation of library test.sol:lib1 pending...', 'creation of library test.sol:lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2 pending...'] txFormat.buildData('testContractLinkLibrary', context.contract, context.output.contracts, true, context.contract.abi[0], '', (error, data) => { if (error) { return st.fails(error) } console.log(data) - var linkedbyteCode = data.dataHex - var libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1'] + const linkedbyteCode = data.dataHex + let libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1'] st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), fakeDeployedContracts['lib1'].replace('0x', '')) st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), fakeDeployedContracts['lib1'].replace('0x', '')) @@ -182,22 +182,22 @@ function testLinkLibrary (st, fakeDeployedContracts, callbackDeployLibraries) { } function testLinkLibrary2 (st, callbackDeployLibraries) { - var librariesReference = { + const librariesReference = { 'test.sol': { 'lib1': '0xf7a10e525d4b168f45f74db1b61f63d3e7619e11', 'lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2': '0xf7a10e525d4b168f45f74db1b61f63d3e7619e33' } } - var data = '608060405234801561001057600080fd5b506101e2806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c80636d4ce63c14610030575b600080fd5b61003861003a565b005b73f7a10e525d4b168f45f74db1b61f63d3e7619e116344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561007e57600080fd5b505af4158015610092573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e336344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b1580156100da57600080fd5b505af41580156100ee573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e336344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561013657600080fd5b505af415801561014a573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e116344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561019257600080fd5b505af41580156101a6573d6000803e3d6000fd5b5050505056fea264697066735822122007784c53df7f324243100f6642d889a08a88831c3811dd13eebe3163b7eb2e5464736f6c63430006000033' + const data = '608060405234801561001057600080fd5b506101e2806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c80636d4ce63c14610030575b600080fd5b61003861003a565b005b73f7a10e525d4b168f45f74db1b61f63d3e7619e116344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561007e57600080fd5b505af4158015610092573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e336344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b1580156100da57600080fd5b505af41580156100ee573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e336344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561013657600080fd5b505af415801561014a573d6000803e3d6000fd5b5050505073f7a10e525d4b168f45f74db1b61f63d3e7619e116344733ae16040518163ffffffff1660e01b815260040160006040518083038186803b15801561019257600080fd5b505af41580156101a6573d6000803e3d6000fd5b5050505056fea264697066735822122007784c53df7f324243100f6642d889a08a88831c3811dd13eebe3163b7eb2e5464736f6c63430006000033' - var deployMsg = ['creation of library test.sol:lib1 pending...', + const deployMsg = ['creation of library test.sol:lib1 pending...', 'creation of library test.sol:lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2 pending...'] txFormat.encodeConstructorCallAndLinkLibraries(context.contract, '', context.contract.abi[0], librariesReference, context.contract.evm.bytecode.linkReferences, (error, result) => { console.log(error, result) st.equal(data, result.dataHex) - var linkedbyteCode = result.dataHex - var libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1'] + const linkedbyteCode = result.dataHex + let libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1'] st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), librariesReference['test.sol']['lib1'].replace('0x', '')) st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), librariesReference['test.sol']['lib1'].replace('0x', '')) libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2_lib2'] @@ -208,8 +208,8 @@ function testLinkLibrary2 (st, callbackDeployLibraries) { txFormat.encodeConstructorCallAndDeployLibraries('testContractLinkLibrary', context.contract, context.output.contracts, '', context.contract.abi[0], (error, result) => { console.log(error, result) st.equal(data, result.dataHex) - var linkedbyteCode = result.dataHex - var libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1'] + const linkedbyteCode = result.dataHex + let libReference = context.contract.evm.bytecode.linkReferences['test.sol']['lib1'] st.equal(linkedbyteCode.substr(2 * libReference[0].start, 40), librariesReference['test.sol']['lib1'].replace('0x', '')) st.equal(linkedbyteCode.substr(2 * libReference[1].start, 40), librariesReference['test.sol']['lib1'].replace('0x', '')) @@ -232,9 +232,9 @@ tape('EncodeParameter', function (t) { }) function encodeFunctionCallTest (st) { - var output = compiler.compile(compilerInput(encodeFunctionCall)) + let output = compiler.compile(compilerInput(encodeFunctionCall)) output = JSON.parse(output) - var contract = output.contracts['test.sol']['testContractLinkLibrary'] + const contract = output.contracts['test.sol']['testContractLinkLibrary'] txFormat.encodeFunctionCall('123, "test string"', contract.abi[0], (error, encoded) => { console.log(error) st.equal(encoded.dataHex, '0x805da4ad000000000000000000000000000000000000000000000000000000000000007b0000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000b7465737420737472696e67000000000000000000000000000000000000000000') @@ -246,31 +246,31 @@ function encodeFunctionCallTest (st) { tape('test fallback function', function (t) { t.test('(fallback)', function (st) { st.plan(2) - var output = compiler.compile(compilerInput(fallbackFunction)) + let output = compiler.compile(compilerInput(fallbackFunction)) output = JSON.parse(output) - var contract = output.contracts['test.sol']['fallbackFunctionContract'] + const contract = output.contracts['test.sol']['fallbackFunctionContract'] st.equal(txHelper.encodeFunctionId(contract.abi[1]), '0x805da4ad') st.equal(txHelper.encodeFunctionId(contract.abi[0]), '0x') }) }) tape('test abiEncoderV2', function (t) { - var functionId = '0x56d89238' - var encodedData = '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000170000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000042ed123b0bd8203c2700000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000090746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f00000000000000000000000000000000' - var value1 = '1' - var value2 = '1234567890123456789543' - var value3 = 'test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_' - var decodedData = `[${value1}, ${value2}, "${value3}"], 23` + const functionId = '0x56d89238' + const encodedData = '0x000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000170000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000042ed123b0bd8203c2700000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000090746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f746573745f737472696e675f00000000000000000000000000000000' + const value1 = '1' + const value2 = '1234567890123456789543' + const value3 = 'test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_test_string_' + const decodedData = `[${value1}, ${value2}, "${value3}"], 23` t.test('(abiEncoderV2)', function (st) { st.plan(2) - var output = compiler.compile(compilerInput(abiEncoderV2)) + let output = compiler.compile(compilerInput(abiEncoderV2)) output = JSON.parse(output) - var contract = output.contracts['test.sol']['test'] + let contract = output.contracts['test.sol']['test'] txFormat.encodeFunctionCall(decodedData, contract.abi[0], (error, encoded) => { console.log(error) st.equal(encoded.dataHex, functionId + encodedData.replace('0x', '')) }) - var decoded = txFormat.decodeResponse(util.hexToIntArray(encodedData), contract.abi[0]) + let decoded = txFormat.decodeResponse(util.hexToIntArray(encodedData), contract.abi[0]) console.log(decoded) st.equal(decoded[0], `tuple(uint256,uint256,string): ${value1},${value2},${value3}`) }) @@ -286,26 +286,26 @@ tape('test abiEncoderV2 array of tuple', function (t) { */ st.plan(2) - var output = compiler.compile(compilerInput(abiEncoderV2ArrayOfTuple)) + let output = compiler.compile(compilerInput(abiEncoderV2ArrayOfTuple)) output = JSON.parse(output) - var contract = output.contracts['test.sol']['test'] + const contract = output.contracts['test.sol']['test'] txFormat.encodeParams('[34, "test"]', contract.abi[1], (error, encoded) => { console.log(error) - var decoded = txFormat.decodeResponse(util.hexToIntArray(encoded.dataHex), contract.abi[1]) + const decoded = txFormat.decodeResponse(util.hexToIntArray(encoded.dataHex), contract.abi[1]) console.log(decoded) st.equal(decoded[0], 'tuple(uint256,string): _strucmts 34,test') }) txFormat.encodeParams('[[34, "test"], [123, "test2"]]', contract.abi[2], (error, encoded) => { console.log(error) - var decoded = txFormat.decodeResponse(util.hexToIntArray(encoded.dataHex), contract.abi[2]) + const decoded = txFormat.decodeResponse(util.hexToIntArray(encoded.dataHex), contract.abi[2]) console.log(decoded) st.equal(decoded[0], 'tuple(uint256,string)[]: strucmts 34,test,123,test2') }) }) }) -var uintContract = `contract uintContractTest { +const uintContract = `contract uintContractTest { uint _tp; address _ap; function test(uint _t, address _a, uint _i) public { @@ -314,7 +314,7 @@ var uintContract = `contract uintContractTest { } }` -var stringContract = `contract stringContractTest { +const stringContract = `contract stringContractTest { string _tp; address _ap; function test(string memory _t, address _a, string memory _i) public { @@ -323,7 +323,7 @@ var stringContract = `contract stringContractTest { } }` -var arrayContract = `contract arrayContractTest { +const arrayContract = `contract arrayContractTest { string _sp; address _ap; uint _up; @@ -339,7 +339,7 @@ var arrayContract = `contract arrayContractTest { } }` -var nestedArrayContract = `contract nestedArrayContractTest { +const nestedArrayContract = `contract nestedArrayContractTest { uint public co; string public str; bool public b1; @@ -353,7 +353,7 @@ var nestedArrayContract = `contract nestedArrayContractTest { } }` -var deploySimpleLib = `pragma solidity >= 0.5.0 < 0.7.0; +const deploySimpleLib = `pragma solidity >= 0.5.0 < 0.7.0; library lib1 { function getEmpty () public { @@ -374,14 +374,14 @@ contract testContractLinkLibrary { } }` -var encodeFunctionCall = `pragma solidity >= 0.5.0 < 0.7.0; +const encodeFunctionCall = `pragma solidity >= 0.5.0 < 0.7.0; contract testContractLinkLibrary { function get (uint _p, string memory _o) public { } }` -var fallbackFunction = `pragma solidity >= 0.5.0 < 0.7.0; +const fallbackFunction = `pragma solidity >= 0.5.0 < 0.7.0; contract fallbackFunctionContract { function get (uint _p, string memory _o) public { @@ -390,7 +390,7 @@ contract fallbackFunctionContract { fallback () external {} }` -var abiEncoderV2 = `pragma experimental ABIEncoderV2; +const abiEncoderV2 = `pragma experimental ABIEncoderV2; contract test { struct p { @@ -410,7 +410,7 @@ contract test { } }` -var abiEncoderV2ArrayOfTuple = `pragma experimental ABIEncoderV2; +const abiEncoderV2ArrayOfTuple = `pragma experimental ABIEncoderV2; contract test { struct MyStruct {uint256 num; string _string;} diff --git a/remix-lib/test/txHelper.js b/remix-lib/test/txHelper.js index 7122be43b3..039ec6e83a 100644 --- a/remix-lib/test/txHelper.js +++ b/remix-lib/test/txHelper.js @@ -1,10 +1,10 @@ 'use strict' -var tape = require('tape') -var txHelper = require('../src/execution/txHelper') +const tape = require('tape') +const txHelper = require('../src/execution/txHelper') tape('getFunction', function (st) { st.plan(5) - var fn = txHelper.getFunction(JSON.parse(abi), 'o((address,uint256))') + let fn = txHelper.getFunction(JSON.parse(abi), 'o((address,uint256))') st.equal(fn.name, 'o') fn = txHelper.getFunction(JSON.parse(abi), 'i(bytes32)') @@ -20,7 +20,7 @@ tape('getFunction', function (st) { st.equal(fn.type, 'fallback') }) -var abi = `[ +const abi = `[ { "constant": false, "inputs": [ diff --git a/remix-lib/test/util.js b/remix-lib/test/util.js index 7ca502e3f8..35577a009a 100644 --- a/remix-lib/test/util.js +++ b/remix-lib/test/util.js @@ -1,12 +1,12 @@ 'use strict' -var tape = require('tape') -var util = require('../src/util') +const tape = require('tape') +const util = require('../src/util') tape('Util', function (t) { t.test('lowerbound', function (st) { st.plan(7) - var array = [2, 5, 8, 9, 45, 56, 78] - var lowerBound = util.findLowerBound(10, array) + let array = [2, 5, 8, 9, 45, 56, 78] + let lowerBound = util.findLowerBound(10, array) st.equal(lowerBound, 3) lowerBound = util.findLowerBound(3, array) @@ -33,14 +33,14 @@ tape('Util', function (t) { tape('util.groupBy on valid input', function (t) { t.plan(1) - var result = util.groupBy([ + const result = util.groupBy([ {category: 'GAS', name: 'a'}, {category: 'SEC', name: 'b'}, {category: 'GAS', name: 'c'} ], 'category') - var expectedResult = { + const expectedResult = { 'GAS': [ {category: 'GAS', name: 'a'}, {category: 'GAS', name: 'c'} @@ -63,7 +63,7 @@ tape('util.concatWithSeperator valid output', function (t) { tape('util.escapeRegExp', function (t) { t.plan(3) - var original = 'function (uint256) returns (bool)' + const original = 'function (uint256) returns (bool)' t.equal(util.escapeRegExp('abcd'), 'abcd', 'String with no regex') t.equal(util.escapeRegExp(original), 'function \\(uint256\\) returns \\(bool\\)', 'function string with regex') t.ok(new RegExp(util.escapeRegExp(original)).test(original), 'should still test for original string') @@ -71,9 +71,9 @@ tape('util.escapeRegExp', function (t) { tape('util.compareByteCode', function (t) { t.plan(1) - var address = 'c2a9cef5420203c2672f0e4325cca774893cca98' - var nullAddress = '0000000000000000000000000000000000000000' - var deployedLibraryByteCode = '0x73c2a9cef5420203c2672f0e4325cca774893cca983014608060405260043610610058576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063f26ea02c1461005d575b600080fd5b81801561006957600080fd5b506100886004803603810190808035906020019092919050505061008a565b005b600081600101600060648110151561009e57fe5b600502016002018190555060008160010160006064811015156100bd57fe5b600502016004018190555060008160010160006064811015156100dc57fe5b6005020160030181905550600081600001819055506001816101f501819055816101f601819055506064816101f70181905550505600a165627a7a723058203a6f106db7413fd9cad962bc12ba2327799d6b1334335f7bb854eab04200b3bf0029' + const address = 'c2a9cef5420203c2672f0e4325cca774893cca98' + const nullAddress = '0000000000000000000000000000000000000000' + const deployedLibraryByteCode = '0x73c2a9cef5420203c2672f0e4325cca774893cca983014608060405260043610610058576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063f26ea02c1461005d575b600080fd5b81801561006957600080fd5b506100886004803603810190808035906020019092919050505061008a565b005b600081600101600060648110151561009e57fe5b600502016002018190555060008160010160006064811015156100bd57fe5b600502016004018190555060008160010160006064811015156100dc57fe5b6005020160030181905550600081600001819055506001816101f501819055816101f601819055506064816101f70181905550505600a165627a7a723058203a6f106db7413fd9cad962bc12ba2327799d6b1334335f7bb854eab04200b3bf0029' t.ok(util.compareByteCode(deployedLibraryByteCode, deployedLibraryByteCode.replace(address, nullAddress)), 'library bytecode should be the same') })