git4refactor
filip mertens 7 months ago
commit 6cddc4a210
  1. 3
      apps/circuit-compiler/.eslintrc
  2. 4
      apps/circuit-compiler/src/app/contexts/index.ts
  3. 2
      apps/circuit-compiler/src/app/reducers/state.ts
  4. 10
      apps/circuit-compiler/src/app/services/circomPluginClient.ts
  5. 2
      apps/circuit-compiler/src/app/types/index.ts
  6. 3
      apps/debugger/.eslintrc
  7. 6
      apps/debugger/src/app/debugger.ts
  8. 3
      apps/doc-gen/.eslintrc
  9. 6
      apps/doc-gen/src/app/docgen-client.ts
  10. 72
      apps/doc-gen/src/app/docgen/common/properties.ts
  11. 7
      apps/doc-gen/src/app/docgen/templates.ts
  12. 18
      apps/doc-gen/src/app/docgen/utils/memoized-getter.ts
  13. 8
      apps/doc-gen/src/app/docgen/utils/natspec.ts
  14. 2
      apps/doc-gen/src/app/docgen/utils/normalizeContractPath.ts
  15. 3
      apps/doc-viewer/.eslintrc
  16. 3
      apps/etherscan/.eslintrc
  17. 8
      apps/etherscan/src/app/EtherscanPluginClient.ts
  18. 6
      apps/etherscan/src/app/utils/utilities.ts
  19. 14
      apps/etherscan/src/app/utils/verify.ts
  20. 3
      apps/learneth/.eslintrc
  21. 4
      apps/learneth/src/redux/hooks.ts
  22. 8
      apps/learneth/src/redux/models/loading.ts
  23. 40
      apps/learneth/src/redux/models/remixide.ts
  24. 26
      apps/learneth/src/redux/models/workshop.ts
  25. 6
      apps/learneth/src/redux/store.ts
  26. 8
      apps/learneth/src/remix-client.ts
  27. 3
      apps/remix-ide/src/app/editor/editor.js
  28. 7
      apps/remix-ide/src/app/files/dgitProvider.ts
  29. 3
      apps/remix-ide/src/remixAppManager.js
  30. 18
      apps/solhint/.eslintrc
  31. 3
      apps/solhint/src/app/SolhintPluginClient.ts
  32. 5
      apps/solhint/src/index.d.ts
  33. 3
      apps/solidity-compiler/.eslintrc
  34. 2
      apps/solidity-compiler/src/app/compiler.ts
  35. 264
      apps/vyper/src/app/utils/types.ts
  36. 3
      apps/walletconnect/.eslintrc
  37. 22
      apps/walletconnect/src/services/WalletConnectRemixClient.ts
  38. 2
      libs/ghaction-helper/src/artifacts-helper.ts
  39. 2
      libs/ghaction-helper/src/ethers.ts
  40. 6
      libs/ghaction-helper/src/methods.ts
  41. 11
      libs/remix-analyzer/test/analysis/staticAnalysisCommon-test.ts
  42. 4
      libs/remix-analyzer/test/analysis/staticAnalysisIntegration-test-0.4.24.ts
  43. 3
      libs/remix-analyzer/test/analysis/staticAnalysisIntegration-test-0.5.0.ts
  44. 6
      libs/remix-analyzer/test/analysis/staticAnalysisIssues-test-0.4.24.ts
  45. 2
      libs/remix-analyzer/test/analysis/staticAnalysisIssues-test-0.5.0.ts
  46. 2
      libs/remix-astwalker/tests/resources/legacyAST.ts
  47. 1
      libs/remix-astwalker/tests/resources/newAST.ts
  48. 20
      libs/remix-core-plugin/src/lib/compiler-artefacts.ts
  49. 4
      libs/remix-core-plugin/src/lib/compiler-content-imports.ts
  50. 4
      libs/remix-core-plugin/src/lib/compiler-fetch-and-compile.ts
  51. 10
      libs/remix-core-plugin/src/lib/compiler-metadata.ts
  52. 1
      libs/remix-core-plugin/src/lib/constants/uups.ts
  53. 2
      libs/remix-core-plugin/src/lib/gist-handler.ts
  54. 4
      libs/remix-core-plugin/src/lib/openzeppelin-proxy.ts
  55. 10
      libs/remix-debug/src/Ethdebugger.ts
  56. 10
      libs/remix-debug/src/debugger/VmDebugger.ts
  57. 8
      libs/remix-debug/src/debugger/debugger.ts
  58. 2
      libs/remix-debug/src/debugger/solidityState.ts
  59. 2
      libs/remix-debug/src/debugger/stepManager.ts
  60. 4
      libs/remix-debug/src/init.ts
  61. 18
      libs/remix-debug/src/solidity-decoder/internalCallTree.ts
  62. 2
      libs/remix-debug/src/solidity-decoder/solidityProxy.ts
  63. 2
      libs/remix-debug/src/trace/traceAnalyser.ts
  64. 2
      libs/remix-debug/src/trace/traceManager.ts
  65. 2
      libs/remix-debug/test.ts
  66. 2
      libs/remix-debug/test/codeManager.ts
  67. 12
      libs/remix-debug/test/debugger.ts
  68. 2
      libs/remix-debug/test/decoder/contracts/calldata.ts
  69. 2
      libs/remix-debug/test/decoder/contracts/intLocal.ts
  70. 2
      libs/remix-debug/test/decoder/contracts/miscLocal.ts
  71. 2
      libs/remix-debug/test/decoder/contracts/structArrayLocal.ts
  72. 6
      libs/remix-debug/test/decoder/localDecoder.ts
  73. 7
      libs/remix-debug/test/decoder/localsTests/calldata.ts
  74. 28
      libs/remix-debug/test/decoder/localsTests/int.ts
  75. 12
      libs/remix-debug/test/decoder/localsTests/misc.ts
  76. 10
      libs/remix-debug/test/decoder/localsTests/misc2.ts
  77. 26
      libs/remix-debug/test/decoder/localsTests/structArray.ts
  78. 8
      libs/remix-debug/test/decoder/stateTests/mapping.ts
  79. 4
      libs/remix-debug/test/helpers/compilerHelper.ts
  80. 41
      libs/remix-debug/test/resources/ast.ts
  81. 4
      libs/remix-debug/test/resources/testWeb3.ts
  82. 30
      libs/remix-debug/test/sourceLocationTracker.ts
  83. 2
      libs/remix-debug/test/traceManager.ts
  84. 3
      libs/remix-debug/test/vmCall.ts
  85. 18
      libs/remix-simulator/src/VmProxy.ts
  86. 2
      libs/remix-simulator/src/methods/accounts.ts
  87. 4
      libs/remix-simulator/src/methods/blocks.ts
  88. 6
      libs/remix-simulator/src/methods/transactions.ts
  89. 12
      libs/remix-simulator/src/provider.ts
  90. 2
      libs/remix-simulator/src/server.ts
  91. 19
      libs/remix-simulator/src/vm-context.ts
  92. 8
      libs/remix-simulator/test/blocks.ts
  93. 8
      libs/remix-simulator/test/events.ts
  94. 14
      libs/remix-simulator/test/misc.ts
  95. 2
      libs/remix-simulator/test/transactions.ts
  96. 2
      libs/remix-solidity/src/compiler/compiler-input.ts
  97. 2
      libs/remix-solidity/src/compiler/compiler.ts
  98. 2
      libs/remix-solidity/src/compiler/helper.ts
  99. 2
      libs/remix-solidity/src/compiler/types.ts
  100. 2
      libs/remix-solidity/tests/compiler-input.spec.ts
  101. Some files were not shown because too many files have changed in this diff Show More

@ -0,0 +1,3 @@
{
"extends": "../../.eslintrc.json",
}

@ -1,4 +1,4 @@
import {createContext} from 'react' import { createContext } from 'react'
import {ICircuitAppContext} from '../types' import { ICircuitAppContext } from '../types'
export const CircuitAppContext = createContext<ICircuitAppContext>({} as ICircuitAppContext) export const CircuitAppContext = createContext<ICircuitAppContext>({} as ICircuitAppContext)

@ -1,4 +1,4 @@
import {Actions, AppState} from '../types' import { Actions, AppState } from '../types'
import { compiler_list } from 'circom_wasm' import { compiler_list } from 'circom_wasm'
export const appInitialState: AppState = { export const appInitialState: AppState = {

@ -163,7 +163,7 @@ export class CircomPluginClient extends PluginClient {
} else { } else {
this.lastCompiledFile = path this.lastCompiledFile = path
const fileName = extractNameFromKey(path) const fileName = extractNameFromKey(path)
this.lastCompiledCircuitPath = extractParentFromKey(path) + "/.bin/" + fileName.replace('circom', 'wasm') this.lastCompiledCircuitPath = extractParentFromKey(path) + "/.bin/" + fileName.replace('circom', 'wasm')
// @ts-ignore // @ts-ignore
await this.call('fileManager', 'writeFile', this.lastCompiledCircuitPath, circuitProgram, { encoding: null }) await this.call('fileManager', 'writeFile', this.lastCompiledCircuitPath, circuitProgram, { encoding: null })
@ -179,7 +179,7 @@ export class CircomPluginClient extends PluginClient {
this.internalEvents.emit('circuit_compiling_done', []) this.internalEvents.emit('circuit_compiling_done', [])
} }
circuitApi.log().map(log => { circuitApi.log().map(log => {
log && this.call('terminal', 'log', { type: 'log', value: log }) log && this.call('terminal', 'log', { type: 'log', value: log })
}) })
// @ts-ignore // @ts-ignore
this.call('terminal', 'log', { type: 'typewritersuccess', value: 'Everything went okay' }) this.call('terminal', 'log', { type: 'typewritersuccess', value: 'Everything went okay' })
@ -222,11 +222,11 @@ export class CircomPluginClient extends PluginClient {
this.internalEvents.emit('circuit_generating_r1cs_done') this.internalEvents.emit('circuit_generating_r1cs_done')
const fileName = extractNameFromKey(path) const fileName = extractNameFromKey(path)
const writePath = extractParentFromKey(path) + "/.bin/" + fileName.replace('circom', 'r1cs') const writePath = extractParentFromKey(path) + "/.bin/" + fileName.replace('circom', 'r1cs')
// @ts-ignore // @ts-ignore
await this.call('fileManager', 'writeFile', writePath, r1csProgram, true) await this.call('fileManager', 'writeFile', writePath, r1csProgram, true)
r1csApi.log().map(log => { r1csApi.log().map(log => {
log && this.call('terminal', 'log', { type: 'log', value: log }) log && this.call('terminal', 'log', { type: 'log', value: log })
}) })
// @ts-ignore // @ts-ignore
this.call('terminal', 'log', { type: 'typewritersuccess', value: 'Everything went okay' }) this.call('terminal', 'log', { type: 'typewritersuccess', value: 'Everything went okay' })
@ -339,7 +339,7 @@ export class CircomPluginClient extends PluginClient {
absFilePath = include.startsWith('circomlib') ? absFilePath.substring(1) : absFilePath absFilePath = include.startsWith('circomlib') ? absFilePath.substring(1) : absFilePath
if (!blackPath.includes(absFilePath)) { if (!blackPath.includes(absFilePath)) {
if(!includeName.startsWith('circomlib')) { if (!includeName.startsWith('circomlib')) {
dependencyContent = dependencyContent.replace(`${includeName}`, `${absFilePath}`) dependencyContent = dependencyContent.replace(`${includeName}`, `${absFilePath}`)
return absFilePath return absFilePath
} }

@ -1,5 +1,5 @@
import { compiler_list } from 'circom_wasm' import { compiler_list } from 'circom_wasm'
import {Dispatch} from 'react' import { Dispatch } from 'react'
import type { CircomPluginClient } from '../services/circomPluginClient' import type { CircomPluginClient } from '../services/circomPluginClient'
export type CompilerStatus = "compiling" | "generating" | "computing" | "idle" | "errored" | "warning" export type CompilerStatus = "compiling" | "generating" | "computing" | "idle" | "errored" | "warning"

@ -0,0 +1,3 @@
{
"extends": "../../.eslintrc.json",
}

@ -1,13 +1,13 @@
import { PluginClient } from "@remixproject/plugin"; import { PluginClient } from "@remixproject/plugin";
import { createClient } from "@remixproject/plugin-webview"; import { createClient } from "@remixproject/plugin-webview";
import { IDebuggerApi, LineColumnLocation, import { IDebuggerApi, LineColumnLocation,
onBreakpointClearedListener, onBreakpointAddedListener, onEditorContentChanged, onEnvChangedListener, TransactionReceipt } from '@remix-ui/debugger-ui' onBreakpointClearedListener, onBreakpointAddedListener, onEditorContentChanged, onEnvChangedListener, TransactionReceipt } from '@remix-ui/debugger-ui'
import { DebuggerApiMixin } from '@remix-ui/debugger-ui' import { DebuggerApiMixin } from '@remix-ui/debugger-ui'
import { CompilerAbstract } from '@remix-project/remix-solidity' import { CompilerAbstract } from '@remix-project/remix-solidity'
export class DebuggerClientApi extends DebuggerApiMixin(PluginClient) { export class DebuggerClientApi extends DebuggerApiMixin(PluginClient) {
constructor () { constructor () {
super() super()
createClient(this as any) createClient(this as any)
this.initDebuggerApi() this.initDebuggerApi()
} }

@ -0,0 +1,3 @@
{
"extends": "../../.eslintrc.json",
}

@ -17,7 +17,7 @@ export class DocGenClient extends PluginClient {
public docs: string[] = [] public docs: string[] = []
private fileName: string = '' private fileName: string = ''
private contractPath: string = '' private contractPath: string = ''
constructor() { constructor() {
super() super()
this.eventEmitter = new EventEmitter() this.eventEmitter = new EventEmitter()
@ -30,7 +30,7 @@ export class DocGenClient extends PluginClient {
async setListeners() { async setListeners() {
this.currentTheme = await this.call('theme', 'currentTheme') this.currentTheme = await this.call('theme', 'currentTheme')
this.on('theme', 'themeChanged', (theme: any) => { this.on('theme', 'themeChanged', (theme: any) => {
this.currentTheme = theme this.currentTheme = theme
this.eventEmitter.emit('themeChanged', this.currentTheme) this.eventEmitter.emit('themeChanged', this.currentTheme)
@ -50,7 +50,7 @@ export class DocGenClient extends PluginClient {
} }
const segmentedPathList = normalizeContractPath(fileName) const segmentedPathList = normalizeContractPath(fileName)
this.fileName = segmentedPathList[segmentedPathList.length - 1] this.fileName = segmentedPathList[segmentedPathList.length - 1]
this.contractPath = segmentedPathList[0] this.contractPath = segmentedPathList[0]
this.eventEmitter.emit('compilationFinished', this.build, this.fileName) this.eventEmitter.emit('compilationFinished', this.build, this.fileName)
}) })
} }

@ -36,47 +36,47 @@ export function fullName ({ item, contract }: DocItemContext): string {
export function signature ({ item }: DocItemContext): string | undefined { export function signature ({ item }: DocItemContext): string | undefined {
switch (item.nodeType) { switch (item.nodeType) {
case 'ContractDefinition': case 'ContractDefinition':
return undefined; return undefined;
case 'FunctionDefinition': { case 'FunctionDefinition': {
const { kind, name } = item; const { kind, name } = item;
const params = item.parameters.parameters; const params = item.parameters.parameters;
const returns = item.returnParameters.parameters; const returns = item.returnParameters.parameters;
const head = (kind === 'function' || kind === 'freeFunction') ? [kind, name].join(' ') : kind; const head = (kind === 'function' || kind === 'freeFunction') ? [kind, name].join(' ') : kind;
const res = [ const res = [
`${head}(${params.map(formatVariable).join(', ')})`, `${head}(${params.map(formatVariable).join(', ')})`,
item.visibility, item.visibility,
]; ];
if (item.stateMutability !== 'nonpayable') { if (item.stateMutability !== 'nonpayable') {
res.push(item.stateMutability); res.push(item.stateMutability);
}
if (item.virtual) {
res.push('virtual');
}
if (returns.length > 0) {
res.push(`returns (${returns.map(formatVariable).join(', ')})`);
}
return res.join(' ');
} }
if (item.virtual) {
case 'EventDefinition': { res.push('virtual');
const params = item.parameters.parameters;
return `event ${item.name}(${params.map(formatVariable).join(', ')})`;
} }
if (returns.length > 0) {
case 'ErrorDefinition': { res.push(`returns (${returns.map(formatVariable).join(', ')})`);
const params = item.parameters.parameters;
return `error ${item.name}(${params.map(formatVariable).join(', ')})`;
} }
return res.join(' ');
}
case 'ModifierDefinition': { case 'EventDefinition': {
const params = item.parameters.parameters; const params = item.parameters.parameters;
return `modifier ${item.name}(${params.map(formatVariable).join(', ')})`; return `event ${item.name}(${params.map(formatVariable).join(', ')})`;
} }
case 'ErrorDefinition': {
const params = item.parameters.parameters;
return `error ${item.name}(${params.map(formatVariable).join(', ')})`;
}
case 'ModifierDefinition': {
const params = item.parameters.parameters;
return `modifier ${item.name}(${params.map(formatVariable).join(', ')})`;
}
case 'VariableDeclaration': case 'VariableDeclaration':
return formatVariable(item); return formatVariable(item);
} }
} }

@ -3,7 +3,7 @@ import { mapKeys } from './utils/map-keys';
import { DocItemContext } from './site'; import { DocItemContext } from './site';
import * as defaultProperties from './common/properties'; import * as defaultProperties from './common/properties';
import * as themeHelpers from './themes/markdown/helpers' import * as themeHelpers from './themes/markdown/helpers'
const common = require('./themes/markdown/common.hbs'); const common = require('./themes/markdown/common.hbs');
const contract = require('./themes/markdown/contract.hbs'); const contract = require('./themes/markdown/contract.hbs');
@ -45,7 +45,6 @@ export async function loadTemplates(defaultTheme: string, root: string, userTemp
properties: { ...defaultProperties }, properties: { ...defaultProperties },
}; };
// Add partials and helpers from all themes, prefixed with the theme name. // Add partials and helpers from all themes, prefixed with the theme name.
for (const [themeName, theme] of Object.entries(themes)) { for (const [themeName, theme] of Object.entries(themes)) {
const addPrefix = (k: string) => `${themeName}/${k}`; const addPrefix = (k: string) => `${themeName}/${k}`;
@ -86,7 +85,7 @@ async function readPartials() {
} }
async function readHelpers(name: string) { async function readHelpers(name: string) {
const helpers: Record<string, (...args: any[]) => any> = {}; const helpers: Record<string, (...args: any[]) => any> = {};
for (const name in themeHelpers) { for (const name in themeHelpers) {
@ -94,7 +93,7 @@ async function readHelpers(name: string) {
helpers[name] = themeHelpers[name]; helpers[name] = themeHelpers[name];
} }
} }
return helpers; return helpers;
} }

@ -6,17 +6,17 @@ export function defineGetterMemoized<K extends keyof any, T, O extends { [k in K
enumerable: true, enumerable: true,
get() { get() {
switch (state) { switch (state) {
case 'done': case 'done':
return value; return value;
case 'doing': case 'doing':
throw new Error("Detected recursion"); throw new Error("Detected recursion");
case 'todo': case 'todo':
state = 'doing'; state = 'doing';
value = getter(); value = getter();
state = 'done'; state = 'done';
return value; return value;
} }
} }
}); });

@ -34,10 +34,10 @@ export function parseNatspec(item: DocItemWithContext): NatSpec {
const docString = docSource !== undefined const docString = docSource !== undefined
? cleanUpDocstringFromSource(docSource) ? cleanUpDocstringFromSource(docSource)
: 'documentation' in item && item.documentation : 'documentation' in item && item.documentation
? typeof item.documentation === 'string' ? typeof item.documentation === 'string'
? item.documentation ? item.documentation
: cleanUpDocstringFromSolc(item.documentation.text) : cleanUpDocstringFromSolc(item.documentation.text)
: ''; : '';
const tagMatches = execAll( const tagMatches = execAll(
/^(?:@(\w+|custom:[a-z][a-z-]*) )?((?:(?!^@(?:\w+|custom:[a-z][a-z-]*) )[^])*)/m, /^(?:@(\w+|custom:[a-z][a-z-]*) )?((?:(?!^@(?:\w+|custom:[a-z][a-z-]*) )[^])*)/m,

@ -4,7 +4,7 @@ export function normalizeContractPath(contractPath: string): string[]{
const filename = paths[paths.length - 1] const filename = paths[paths.length - 1]
let folders = '' let folders = ''
for (let i = 0; i < paths.length - 1; i++) { for (let i = 0; i < paths.length - 1; i++) {
if(i !== paths.length -1) { if (i !== paths.length -1) {
folders += `${paths[i]}/` folders += `${paths[i]}/`
} }
} }

@ -0,0 +1,3 @@
{
"extends": "../../.eslintrc.json",
}

@ -0,0 +1,3 @@
{
"extends": "../../.eslintrc.json",
}

@ -1,7 +1,7 @@
import {PluginClient} from '@remixproject/plugin' import { PluginClient } from '@remixproject/plugin'
import { createClient } from '@remixproject/plugin-webview' import { createClient } from '@remixproject/plugin-webview'
import {verify, EtherScanReturn} from './utils/verify' import { verify, EtherScanReturn } from './utils/verify'
import {getReceiptStatus, getEtherScanApi, getNetworkName, getProxyContractReceiptStatus} from './utils' import { getReceiptStatus, getEtherScanApi, getNetworkName, getProxyContractReceiptStatus } from './utils'
import EventManager from 'events' import EventManager from 'events'
export class EtherscanPluginClient extends PluginClient { export class EtherscanPluginClient extends PluginClient {
@ -46,7 +46,7 @@ export class EtherscanPluginClient extends PluginClient {
async receiptStatus(receiptGuid: string, apiKey: string, isProxyContract: boolean) { async receiptStatus(receiptGuid: string, apiKey: string, isProxyContract: boolean) {
try { try {
const {network, networkId} = await getNetworkName(this) const { network, networkId } = await getNetworkName(this)
if (network === 'vm') { if (network === 'vm') {
throw new Error('Cannot check the receipt status in the selected network') throw new Error('Cannot check the receipt status in the selected network')
} }

@ -4,7 +4,7 @@ import { scanAPIurls } from "./networks"
type RemixClient = PluginClient type RemixClient = PluginClient
/* /*
status: 0=Error, 1=Pass status: 0=Error, 1=Pass
message: OK, NOTOK message: OK, NOTOK
result: explanation result: explanation
*/ */
@ -14,7 +14,7 @@ export type receiptStatus = {
status: string status: string
} }
export const getEtherScanApi = (networkId: any) => { export const getEtherScanApi = (networkId: any) => {
if (!(networkId in scanAPIurls)) { if (!(networkId in scanAPIurls)) {
throw new Error("no known network to verify against") throw new Error("no known network to verify against")
} }
@ -26,7 +26,7 @@ export const getNetworkName = async (client: RemixClient) => {
const network = await client.call("network", "detectNetwork") const network = await client.call("network", "detectNetwork")
if (!network) { if (!network) {
throw new Error("no known network to verify against") throw new Error("no known network to verify against")
} }
return { network: network.name!.toLowerCase(), networkId: network.id } return { network: network.name!.toLowerCase(), networkId: network.id }
} }

@ -23,7 +23,7 @@ export const verify = async (
compilationResultParam: CompilerAbstract, compilationResultParam: CompilerAbstract,
chainRef: number | string, chainRef: number | string,
isProxyContract: boolean, isProxyContract: boolean,
expectedImplAddress: string, expectedImplAddress: string,
client: PluginClient, client: PluginClient,
onVerifiedContract: (value: EtherScanReturn) => void, onVerifiedContract: (value: EtherScanReturn) => void,
setResults: (value: string) => void setResults: (value: string) => void
@ -47,7 +47,7 @@ export const verify = async (
etherscanApi = getEtherScanApi(networkChainId) etherscanApi = getEtherScanApi(networkChainId)
} }
} }
try { try {
const contractMetadata = getContractMetadata( const contractMetadata = getContractMetadata(
// cast from the remix-plugin interface to the solidity one. Should be fixed when remix-plugin move to the remix-project repository // cast from the remix-plugin interface to the solidity one. Should be fixed when remix-plugin move to the remix-project repository
@ -61,7 +61,7 @@ export const verify = async (
message: "Please recompile contract" message: "Please recompile contract"
} }
} }
const contractMetadataParsed = JSON.parse(contractMetadata) const contractMetadataParsed = JSON.parse(contractMetadata)
const fileName = getContractFileName( const fileName = getContractFileName(
@ -146,9 +146,9 @@ export const verify = async (
title: result, title: result,
}) })
const returnValue = { const returnValue = {
message: result, message: result,
succeed: false, succeed: false,
isProxyContract isProxyContract
} }
resetAfter10Seconds(client, setResults) resetAfter10Seconds(client, setResults)
return returnValue return returnValue
@ -184,7 +184,7 @@ export const getContractFileName = (
} }
return fileName return fileName
} }
export const getContractMetadata = ( export const getContractMetadata = (
compilationResult: CompilationResult, compilationResult: CompilationResult,
contractName: string contractName: string

@ -0,0 +1,3 @@
{
"extends": "../../.eslintrc.json",
}

@ -1,5 +1,5 @@
import {useDispatch, type TypedUseSelectorHook, useSelector} from 'react-redux' import { useDispatch, type TypedUseSelectorHook, useSelector } from 'react-redux'
import {type AppDispatch, type RootState} from './store' import { type AppDispatch, type RootState } from './store'
export const useAppDispatch: () => AppDispatch = useDispatch export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

@ -1,11 +1,11 @@
import {type ModelType} from '../store' import { type ModelType } from '../store'
const Model: ModelType = { const Model: ModelType = {
namespace: 'loading', namespace: 'loading',
state: {screen: true}, state: { screen: true },
reducers: { reducers: {
save(state, {payload}) { save(state, { payload }) {
return {...state, ...payload} return { ...state, ...payload }
}, },
}, },
effects: {}, effects: {},

@ -1,7 +1,7 @@
import {toast} from 'react-toastify' import { toast } from 'react-toastify'
import {type ModelType} from '../store' import { type ModelType } from '../store'
import remixClient from '../../remix-client' import remixClient from '../../remix-client'
import {router} from '../../App' import { router } from '../../App'
function getFilePath(file: string): string { function getFilePath(file: string): string {
const name = file.split('/') const name = file.split('/')
@ -17,12 +17,12 @@ const Model: ModelType = {
// theme: '', // theme: '',
}, },
reducers: { reducers: {
save(state, {payload}) { save(state, { payload }) {
return {...state, ...payload} return { ...state, ...payload }
}, },
}, },
effects: { effects: {
*connect(_, {put}) { *connect(_, { put }) {
toast.info('connecting to the REMIX IDE') toast.info('connecting to the REMIX IDE')
yield put({ yield put({
@ -45,7 +45,7 @@ const Model: ModelType = {
yield router.navigate('/home') yield router.navigate('/home')
}, },
*displayFile({payload: step}, {select, put}) { *displayFile({ payload: step }, { select, put }) {
let content = '' let content = ''
let path = '' let path = ''
if (step.solidity?.file) { if (step.solidity?.file) {
@ -73,7 +73,7 @@ const Model: ModelType = {
}, },
}) })
const {detail, selectedId} = yield select((state) => state.workshop) const { detail, selectedId } = yield select((state) => state.workshop)
const workshop = detail[selectedId] const workshop = detail[selectedId]
console.log('loading ', step, workshop) console.log('loading ', step, workshop)
@ -87,7 +87,7 @@ const Model: ModelType = {
yield remixClient.call('fileManager', 'switchFile', `${path}`) yield remixClient.call('fileManager', 'switchFile', `${path}`)
yield put({ yield put({
type: 'remixide/save', type: 'remixide/save',
payload: {errorLoadingFile: false}, payload: { errorLoadingFile: false },
}) })
toast.dismiss() toast.dismiss()
} catch (error) { } catch (error) {
@ -95,7 +95,7 @@ const Model: ModelType = {
toast.error('File could not be loaded. Please try again.') toast.error('File could not be loaded. Please try again.')
yield put({ yield put({
type: 'remixide/save', type: 'remixide/save',
payload: {errorLoadingFile: true}, payload: { errorLoadingFile: true },
}) })
} }
yield put({ yield put({
@ -105,7 +105,7 @@ const Model: ModelType = {
}, },
}) })
}, },
*testStep({payload: step}, {select, put}) { *testStep({ payload: step }, { select, put }) {
yield put({ yield put({
type: 'loading/save', type: 'loading/save',
payload: { payload: {
@ -116,9 +116,9 @@ const Model: ModelType = {
try { try {
yield put({ yield put({
type: 'remixide/save', type: 'remixide/save',
payload: {success: false}, payload: { success: false },
}) })
const {detail, selectedId} = yield select((state) => state.workshop) const { detail, selectedId } = yield select((state) => state.workshop)
const workshop = detail[selectedId] const workshop = detail[selectedId]
@ -141,7 +141,7 @@ const Model: ModelType = {
if (!result) { if (!result) {
yield put({ yield put({
type: 'remixide/save', type: 'remixide/save',
payload: {errors: ['Compiler failed to test this file']}, payload: { errors: ['Compiler failed to test this file']},
}) })
} else { } else {
const success = result.totalFailing === 0 const success = result.totalFailing === 0
@ -149,7 +149,7 @@ const Model: ModelType = {
if (success) { if (success) {
yield put({ yield put({
type: 'remixide/save', type: 'remixide/save',
payload: {errors: [], success: true}, payload: { errors: [], success: true },
}) })
} else { } else {
yield put({ yield put({
@ -164,7 +164,7 @@ const Model: ModelType = {
console.log('TESTING ERROR', err) console.log('TESTING ERROR', err)
yield put({ yield put({
type: 'remixide/save', type: 'remixide/save',
payload: {errors: [String(err)]}, payload: { errors: [String(err)]},
}) })
} }
yield put({ yield put({
@ -174,7 +174,7 @@ const Model: ModelType = {
}, },
}) })
}, },
*showAnswer({payload: step}, {select, put}) { *showAnswer({ payload: step }, { select, put }) {
yield put({ yield put({
type: 'loading/save', type: 'loading/save',
payload: { payload: {
@ -189,7 +189,7 @@ const Model: ModelType = {
const content = step.answer.content const content = step.answer.content
let path = getFilePath(step.answer.file) let path = getFilePath(step.answer.file)
const {detail, selectedId} = yield select((state) => state.workshop) const { detail, selectedId } = yield select((state) => state.workshop)
const workshop = detail[selectedId] const workshop = detail[selectedId]
path = `.learneth/${workshop.name}/${step.name}/${path}` path = `.learneth/${workshop.name}/${step.name}/${path}`
@ -198,7 +198,7 @@ const Model: ModelType = {
} catch (err) { } catch (err) {
yield put({ yield put({
type: 'remixide/save', type: 'remixide/save',
payload: {errors: [String(err)]}, payload: { errors: [String(err)]},
}) })
} }
@ -210,7 +210,7 @@ const Model: ModelType = {
}, },
}) })
}, },
*testSolidityCompiler(_, {put, select}) { *testSolidityCompiler(_, { put, select }) {
try { try {
yield remixClient.call('solidity', 'getCompilationResult') yield remixClient.call('solidity', 'getCompilationResult')
} catch (err) { } catch (err) {

@ -1,10 +1,10 @@
import axios from 'axios' import axios from 'axios'
import {toast} from 'react-toastify' import { toast } from 'react-toastify'
import groupBy from 'lodash/groupBy' import groupBy from 'lodash/groupBy'
import pick from 'lodash/pick' import pick from 'lodash/pick'
import {type ModelType} from '../store' import { type ModelType } from '../store'
import remixClient from '../../remix-client' import remixClient from '../../remix-client'
import {router} from '../../App' import { router } from '../../App'
// const apiUrl = 'http://localhost:3001'; // const apiUrl = 'http://localhost:3001';
const apiUrl = 'https://static.220.14.12.49.clients.your-server.de:3000' const apiUrl = 'https://static.220.14.12.49.clients.your-server.de:3000'
@ -17,12 +17,12 @@ const Model: ModelType = {
selectedId: '', selectedId: '',
}, },
reducers: { reducers: {
save(state, {payload}) { save(state, { payload }) {
return {...state, ...payload} return { ...state, ...payload }
}, },
}, },
effects: { effects: {
*init(_, {put}) { *init(_, { put }) {
const cache = localStorage.getItem('workshop.state') const cache = localStorage.getItem('workshop.state')
if (cache) { if (cache) {
@ -41,7 +41,7 @@ const Model: ModelType = {
}) })
} }
}, },
*loadRepo({payload}, {put, select}) { *loadRepo({ payload }, { put, select }) {
toast.info(`loading ${payload.name}/${payload.branch}`) toast.info(`loading ${payload.name}/${payload.branch}`)
yield put({ yield put({
@ -51,18 +51,18 @@ const Model: ModelType = {
}, },
}) })
const {list, detail} = yield select((state) => state.workshop) const { list, detail } = yield select((state) => state.workshop)
const url = `${apiUrl}/clone/${encodeURIComponent(payload.name)}/${payload.branch}?${Math.random()}` const url = `${apiUrl}/clone/${encodeURIComponent(payload.name)}/${payload.branch}?${Math.random()}`
console.log('loading ', url) console.log('loading ', url)
const {data} = yield axios.get(url) const { data } = yield axios.get(url)
const repoId = `${payload.name}-${payload.branch}` const repoId = `${payload.name}-${payload.branch}`
for (let i = 0; i < data.ids.length; i++) { for (let i = 0; i < data.ids.length; i++) {
const { const {
steps, steps,
metadata: { metadata: {
data: {steps: metadataSteps}, data: { steps: metadataSteps },
}, },
} = data.entities[data.ids[i]] } = data.entities[data.ids[i]]
@ -130,8 +130,8 @@ const Model: ModelType = {
}) })
if (payload.id) { if (payload.id) {
const {detail, selectedId} = workshopState const { detail, selectedId } = workshopState
const {ids, entities} = detail[selectedId] const { ids, entities } = detail[selectedId]
for (let i = 0; i < ids.length; i++) { for (let i = 0; i < ids.length; i++) {
const entity = entities[ids[i]] const entity = entities[ids[i]]
if (entity.metadata.data.id === payload.id || i + 1 === payload.id) { if (entity.metadata.data.id === payload.id || i + 1 === payload.id) {
@ -141,7 +141,7 @@ const Model: ModelType = {
} }
} }
}, },
*resetAll(_, {put}) { *resetAll(_, { put }) {
yield put({ yield put({
type: 'workshop/save', type: 'workshop/save',
payload: { payload: {

@ -1,6 +1,6 @@
import {configureStore, createSlice, type PayloadAction, type Reducer} from '@reduxjs/toolkit' import { configureStore, createSlice, type PayloadAction, type Reducer } from '@reduxjs/toolkit'
import createSagaMiddleware from 'redux-saga' import createSagaMiddleware from 'redux-saga'
import {call, put, takeEvery, delay, select, all, fork, type ForkEffect} from 'redux-saga/effects' import { call, put, takeEvery, delay, select, all, fork, type ForkEffect } from 'redux-saga/effects'
// @ts-expect-error // @ts-expect-error
const context = require.context('./models', false, /\.ts$/) const context = require.context('./models', false, /\.ts$/)
@ -39,7 +39,7 @@ function createReducer(model: ModelType): Reducer {
} }
const rootReducer = models.reduce((prev: any, model: ModelType) => { const rootReducer = models.reduce((prev: any, model: ModelType) => {
return {...prev, [model.namespace]: createReducer(model)} return { ...prev, [model.namespace]: createReducer(model) }
}, {}) }, {})
function watchEffects(model: ModelType): ForkEffect { function watchEffects(model: ModelType): ForkEffect {

@ -1,7 +1,7 @@
import {PluginClient} from '@remixproject/plugin' import { PluginClient } from '@remixproject/plugin'
import {createClient} from '@remixproject/plugin-webview' import { createClient } from '@remixproject/plugin-webview'
import {store} from './redux/store' import { store } from './redux/store'
import {router} from './App' import { router } from './App'
class RemixClient extends PluginClient { class RemixClient extends PluginClient {
constructor() { constructor() {

@ -54,7 +54,8 @@ class Editor extends Plugin {
ts: 'typescript', ts: 'typescript',
move: 'move', move: 'move',
circom: 'circom', circom: 'circom',
nr: 'rust' nr: 'rust',
toml: 'toml'
} }
this.activated = false this.activated = false

@ -571,7 +571,7 @@ class DGitProvider extends Plugin {
const result = await this.call('isogit', 'clone', cmd) const result = await this.call('isogit', 'clone', cmd)
this.call('fs', 'openWindow', folder) this.call('fs', 'openWindow', folder)
return result return result
} catch (e) { } catch (e){
this.call('notification', 'alert', { this.call('notification', 'alert', {
id: 'dgitAlert', id: 'dgitAlert',
message: 'Unexpected error while cloning the repository: \n' + e.toString(), message: 'Unexpected error while cloning the repository: \n' + e.toString(),
@ -708,9 +708,8 @@ class DGitProvider extends Plugin {
this.call('terminal', 'log', { this.call('terminal', 'log', {
type: 'error', type: 'error',
value: `Could not checkout submodule to ${result[0]}` value: `Could not checkout submodule to ${result[0]}`
}) })} else {
} else { this.call('terminal', 'logHtml',`Checked out submodule ${dir} to ${result[0]}`)
this.call('terminal', 'logHtml', `Checked out submodule ${dir} to ${result[0]}`)
} }
} }

@ -76,7 +76,8 @@ let requiredModules = [ // services + layout views + system views
'home', 'home',
'doc-viewer', 'doc-viewer',
'doc-gen', 'doc-gen',
'remix-templates' 'remix-templates',
'solhint'
] ]

@ -0,0 +1,18 @@
{
"extends": "../../.eslintrc.json",
"overrides": [
{
"files": [
"*.ts",
"*.tsx",
"*.js",
"*.jsx"
],
"rules": {
"@nrwl/nx/enforce-module-boundaries": [
"off"
]
}
}
]
}

@ -1,6 +1,7 @@
import { PluginClient } from '@remixproject/plugin' import { PluginClient } from '@remixproject/plugin'
import { createClient } from '@remixproject/plugin-webview' import { createClient } from '@remixproject/plugin-webview'
import EventEmitter from 'events' import EventEmitter from 'events'
// eslint-disable @nrwl/nx/enforce-module-boundaries
import { processStr } from 'solhint' import { processStr } from 'solhint'
import { applyExtends } from 'solhint/lib/config/config-file' import { applyExtends } from 'solhint/lib/config/config-file'
import bestPractises from 'solhint/lib/rules/best-practises' import bestPractises from 'solhint/lib/rules/best-practises'
@ -44,7 +45,7 @@ export class SolHint extends PluginClient {
} }
async lintOnCompilation() { async lintOnCompilation() {
if(!this.triggerLinter) return if (!this.triggerLinter) return
this.on('solidity', 'compilationFinished', async (fileName, source, languageVersion, data) => { this.on('solidity', 'compilationFinished', async (fileName, source, languageVersion, data) => {
const hints = await this.lint(fileName) const hints = await this.lint(fileName)
console.log('after compile', { hints }) console.log('after compile', { hints })

@ -0,0 +1,5 @@
declare module 'solhint' {
export function processStr (inputStr: any, config?: any, fileName?: string)
export function processFile (file: any, config: any)
export function processPath (path: any, config: any)
}

@ -0,0 +1,3 @@
{
"extends": "../../.eslintrc.json"
}

@ -22,7 +22,7 @@ export class CompilerClientApi extends CompilerApiMixin(PluginClient) implements
this.compileTabLogic = new CompileTabLogic(this, this.contentImport) this.compileTabLogic = new CompileTabLogic(this, this.contentImport)
this.compiler = this.compileTabLogic.compiler this.compiler = this.compileTabLogic.compiler
this.compileTabLogic.init() this.compileTabLogic.init()
this.initCompilerApi() this.initCompilerApi()
} }
getCompilerQueryParameters () { getCompilerQueryParameters () {

@ -1,4 +1,4 @@
import {CompilationResult, ABIDescription} from '@remixproject/plugin-api' import { CompilationResult, ABIDescription } from '@remixproject/plugin-api'
export interface VyperCompilationResult { export interface VyperCompilationResult {
status: 'success' status: 'success'
@ -18,7 +18,6 @@ export interface VyperCompilationError {
message: string message: string
} }
export type VyperCompilationResultType = { export type VyperCompilationResultType = {
buildDependencies: any buildDependencies: any
compilers: [ compilers: [
@ -85,68 +84,68 @@ export type VyperCompilationResultType = {
} }
export interface PackageManifest { export interface PackageManifest {
title: string; title: string;
description: string; description: string;
type: TypeEnum; type: TypeEnum;
required: string[]; required: string[];
version: string; version: string;
properties: PackageManifestProperties; properties: PackageManifestProperties;
definitions: Definitions; definitions: Definitions;
} }
export interface Definitions { export interface Definitions {
packageMeta: ByteString; packageMeta: ByteString;
contractType: ByteString; contractType: ByteString;
contractInstance: ContractInstance; contractInstance: ContractInstance;
byteString: ByteString; byteString: ByteString;
bytecodeObject: BytecodeObject; bytecodeObject: BytecodeObject;
linkReference: LinkReference; linkReference: LinkReference;
linkValue: LinkValue; linkValue: LinkValue;
identifier: ByteString; identifier: ByteString;
contractInstanceName: ByteString; contractInstanceName: ByteString;
deployment: Deployment; deployment: Deployment;
packageContractInstanceName: ByteString; packageContractInstanceName: ByteString;
compilerInformation: CompilerInformation; compilerInformation: CompilerInformation;
address: Address; address: Address;
transactionHash: Address; transactionHash: Address;
blockHash: Address; blockHash: Address;
contentURI: ByteString; contentURI: ByteString;
} }
export interface Address { export interface Address {
title: string; title: string;
description: string; description: string;
allOf: AllOf[]; allOf: AllOf[];
} }
export interface AllOf { export interface AllOf {
ref?: string; ref?: string;
minLength?: number; minLength?: number;
maxLength?: number; maxLength?: number;
} }
export interface ByteStringProperties { export interface ByteStringProperties {
contractName?: ByteString; contractName?: ByteString;
deploymentBytecode?: Meta; deploymentBytecode?: Meta;
runtimeBytecode?: Meta; runtimeBytecode?: Meta;
abi?: ByteString; abi?: ByteString;
natspec?: ByteString; natspec?: ByteString;
compiler?: Meta; compiler?: Meta;
authors?: ByteString; authors?: ByteString;
license?: ByteString; license?: ByteString;
description?: ByteString; description?: ByteString;
keywords?: ByteString; keywords?: ByteString;
links?: Links; links?: Links;
} }
export interface ByteString { export interface ByteString {
title: string; title: string;
description?: string; description?: string;
type: TypeEnum; type: TypeEnum;
pattern?: string; pattern?: string;
format?: string; format?: string;
items?: Items; items?: Items;
properties?: ByteStringProperties; properties?: ByteStringProperties;
patternProperties?: { [key: string]: Meta }; patternProperties?: { [key: string]: Meta };
} }
@ -155,29 +154,29 @@ export interface Meta {
} }
export interface Links { export interface Links {
title: string; title: string;
descriptions: string; descriptions: string;
type: TypeEnum; type: TypeEnum;
additionalProperties: AdditionalProperties; additionalProperties: AdditionalProperties;
} }
export interface AdditionalProperties { export interface AdditionalProperties {
type: TypeEnum; type: TypeEnum;
format: string; format: string;
} }
export type TypeEnum = "string" | "array" | "object"; export type TypeEnum = "string" | "array" | "object";
export interface Items { export interface Items {
ref?: string; ref?: string;
type?: TypeEnum; type?: TypeEnum;
} }
export interface BytecodeObject { export interface BytecodeObject {
title: string title: string
type: TypeEnum type: TypeEnum
offsets: number[] offsets: number[]
anyOf: BytecodeObjectAnyOf[] anyOf: BytecodeObjectAnyOf[]
properties: BytecodeObjectProperties properties: BytecodeObjectProperties
bytecode: string bytecode: string
linkReferences?: { offset?: any; length?: number; name?: string}[] linkReferences?: { offset?: any; length?: number; name?: string}[]
@ -188,56 +187,56 @@ export interface BytecodeObjectAnyOf {
} }
export interface BytecodeObjectProperties { export interface BytecodeObjectProperties {
bytecode: Meta; bytecode: Meta;
linkReferences: Link; linkReferences: Link;
linkDependencies: Link; linkDependencies: Link;
} }
export interface Link { export interface Link {
type: TypeEnum; type: TypeEnum;
items: Meta; items: Meta;
} }
export interface CompilerInformation { export interface CompilerInformation {
title: string; title: string;
description: string; description: string;
type: TypeEnum; type: TypeEnum;
required: string[]; required: string[];
properties: CompilerInformationProperties; properties: CompilerInformationProperties;
} }
export interface CompilerInformationProperties { export interface CompilerInformationProperties {
name: Name; name: Name;
version: Name; version: Name;
settings: Name; settings: Name;
} }
export interface Name { export interface Name {
description: string; description: string;
type: TypeEnum; type: TypeEnum;
} }
export interface ContractInstance { export interface ContractInstance {
title: string; title: string;
description: string; description: string;
type: TypeEnum; type: TypeEnum;
required: string[]; required: string[];
properties: ContractInstanceProperties; properties: ContractInstanceProperties;
} }
export interface ContractInstanceProperties { export interface ContractInstanceProperties {
contractType: ByteString; contractType: ByteString;
address: Meta; address: Meta;
transaction: Meta; transaction: Meta;
block: Meta; block: Meta;
runtimeBytecode: Meta; runtimeBytecode: Meta;
compiler: Meta; compiler: Meta;
linkDependencies: ByteString; linkDependencies: ByteString;
} }
export interface Deployment { export interface Deployment {
title: string; title: string;
type: TypeEnum; type: TypeEnum;
patternProperties: DeploymentPatternProperties; patternProperties: DeploymentPatternProperties;
} }
@ -246,36 +245,36 @@ export interface DeploymentPatternProperties {
} }
export interface LinkReference { export interface LinkReference {
title: string; title: string;
description: string; description: string;
type: TypeEnum; type: TypeEnum;
required: string[]; required: string[];
properties: LinkReferenceProperties; properties: LinkReferenceProperties;
} }
export interface LinkReferenceProperties { export interface LinkReferenceProperties {
offsets: Offsets; offsets: Offsets;
length: Length; length: Length;
name: Meta; name: Meta;
} }
export interface Length { export interface Length {
type: string; type: string;
minimum: number; minimum: number;
} }
export interface Offsets { export interface Offsets {
type: TypeEnum; type: TypeEnum;
items: Length; items: Length;
} }
export interface LinkValue { export interface LinkValue {
title: string; title: string;
description: string; description: string;
type: TypeEnum; type: TypeEnum;
required: string[]; required: string[];
properties: LinkValueProperties; properties: LinkValueProperties;
oneOf: OneOf[]; oneOf: OneOf[];
} }
export interface OneOf { export interface OneOf {
@ -283,7 +282,7 @@ export interface OneOf {
} }
export interface OneOfProperties { export interface OneOfProperties {
type: TypeClass; type: TypeClass;
value: PurpleValue; value: PurpleValue;
} }
@ -292,14 +291,14 @@ export interface TypeClass {
} }
export interface PurpleValue { export interface PurpleValue {
ref?: string; ref?: string;
anyOf?: Meta[]; anyOf?: Meta[];
} }
export interface LinkValueProperties { export interface LinkValueProperties {
offsets: Offsets; offsets: Offsets;
type: Name; type: Name;
value: FluffyValue; value: FluffyValue;
} }
export interface FluffyValue { export interface FluffyValue {
@ -307,19 +306,19 @@ export interface FluffyValue {
} }
export interface PackageManifestProperties { export interface PackageManifestProperties {
manifestVersion: ManifestVersion; manifestVersion: ManifestVersion;
packageName: ByteString; packageName: ByteString;
meta: Meta; meta: Meta;
version: Version; version: Version;
sources: Sources; sources: Sources;
contractTypes: ByteString; contractTypes: ByteString;
deployments: ByteString; deployments: ByteString;
buildDependencies: BuildDependencies; buildDependencies: BuildDependencies;
} }
export interface BuildDependencies { export interface BuildDependencies {
title: string; title: string;
type: TypeEnum; type: TypeEnum;
patternProperties: BuildDependenciesPatternProperties; patternProperties: BuildDependenciesPatternProperties;
} }
@ -328,16 +327,16 @@ export interface BuildDependenciesPatternProperties {
} }
export interface ManifestVersion { export interface ManifestVersion {
type: TypeEnum; type: TypeEnum;
title: string; title: string;
description: string; description: string;
default: string; default: string;
enum: string[]; enum: string[];
} }
export interface Sources { export interface Sources {
title: string; title: string;
type: TypeEnum; type: TypeEnum;
patternProperties: SourcesPatternProperties; patternProperties: SourcesPatternProperties;
} }
@ -351,13 +350,13 @@ export interface Empty {
export interface AnyOf { export interface AnyOf {
title?: string; title?: string;
type?: TypeEnum; type?: TypeEnum;
ref?: string; ref?: string;
} }
export interface Version { export interface Version {
title: string; title: string;
type: TypeEnum; type: TypeEnum;
} }
export type CompileFormat = { export type CompileFormat = {
@ -448,7 +447,6 @@ deployments: {
[contractName: string]: ContractInstanceObject [contractName: string]: ContractInstanceObject
} }
} }
export type CompilerInformationObject = { export type CompilerInformationObject = {
@ -496,45 +494,45 @@ export type ContractInstanceObject = {
export type ASTSrc = { export type ASTSrc = {
jumpCode: string; jumpCode: string;
length: number; length: number;
} }
export type Child = { export type Child = {
astType: string; astType: string;
children: Child[]; children: Child[];
classification: number; classification: number;
colOffset: number; colOffset: number;
endColOffset: number; endColOffset: number;
endLineno: number; endLineno: number;
lineno: number; lineno: number;
name?: string; name?: string;
src: ChildSrc; src: ChildSrc;
docStr?: Child; docStr?: Child;
} }
export type ChildSrc = { export type ChildSrc = {
jumpCode: string; jumpCode: string;
length: number; length: number;
start: number; start: number;
} }
export type AST = { export type AST = {
astType: string; astType: string;
children: Child[]; children: Child[];
classification: number; classification: number;
colOffset: number; colOffset: number;
endColOffset: number; endColOffset: number;
endLineno: number; endLineno: number;
lineno: number; lineno: number;
name: string; name: string;
src: ASTSrc; src: ASTSrc;
} }
export type ABI = { export type ABI = {
anonymous?: boolean; anonymous?: boolean;
inputs: any[]; inputs: any[];
name?: string; name?: string;
type: any type: any
stateMutability?: any; stateMutability?: any;
outputs?: any[]; outputs?: any[];
} }

@ -0,0 +1,3 @@
{
"extends": "../../.eslintrc.json",
}

@ -1,9 +1,9 @@
import {PluginClient} from '@remixproject/plugin' import { PluginClient } from '@remixproject/plugin'
import {createClient} from '@remixproject/plugin-webview' import { createClient } from '@remixproject/plugin-webview'
import { createWeb3Modal, defaultConfig } from '@web3modal/ethers5/react' import { createWeb3Modal, defaultConfig } from '@web3modal/ethers5/react'
import { constants } from '../utils/constants' import { constants } from '../utils/constants'
import EventManager from 'events' import EventManager from 'events'
import {PROJECT_ID as projectId, METADATA as metadata} from './constant' import { PROJECT_ID as projectId, METADATA as metadata } from './constant'
import { Chain, RequestArguments } from '../types' import { Chain, RequestArguments } from '../types'
export class WalletConnectRemixClient extends PluginClient { export class WalletConnectRemixClient extends PluginClient {
@ -39,7 +39,7 @@ export class WalletConnectRemixClient extends PluginClient {
metadata, metadata,
rpcUrl: 'https://cloudflare-eth.com' rpcUrl: 'https://cloudflare-eth.com'
}) })
this.web3modal = createWeb3Modal({ projectId, chains: constants.chains, metadata, ethersConfig }) this.web3modal = createWeb3Modal({ projectId, chains: constants.chains, metadata, ethersConfig })
this.ethersConfig = ethersConfig this.ethersConfig = ethersConfig
this.chains = constants.chains this.chains = constants.chains
@ -50,16 +50,16 @@ export class WalletConnectRemixClient extends PluginClient {
subscribeToEvents() { subscribeToEvents() {
this.web3modal.subscribeProvider(({ address, isConnected, chainId })=>{ this.web3modal.subscribeProvider(({ address, isConnected, chainId })=>{
if(isConnected){ if (isConnected){
if (address !== this.currentAccount) { if (address !== this.currentAccount) {
this.currentAccount = address this.currentAccount = address
this.emit('accountsChanged', [address]) this.emit('accountsChanged', [address])
} }
if (this.currentChain !== chainId) { if (this.currentChain !== chainId) {
this.currentChain = chainId this.currentChain = chainId
this.emit('chainChanged', chainId) this.emit('chainChanged', chainId)
} }
}else{ } else {
this.emit('accountsChanged', []) this.emit('accountsChanged', [])
this.currentAccount = '' this.currentAccount = ''
this.emit('chainChanged', 0) this.emit('chainChanged', 0)
@ -106,7 +106,7 @@ export class WalletConnectRemixClient extends PluginClient {
error, error,
id: data.id id: data.id
}) })
} }
} }
return resolve(response) return resolve(response)
}) })
@ -114,16 +114,16 @@ export class WalletConnectRemixClient extends PluginClient {
} else { } else {
try { try {
const message = await provider.request(data) const message = await provider.request(data)
return {jsonrpc: '2.0', result: message, id: data.id} return { jsonrpc: '2.0', result: message, id: data.id }
} catch (e) { } catch (e) {
return {jsonrpc: '2.0', error: { message: e.message, code: -32603 }, id: data.id} return { jsonrpc: '2.0', error: { message: e.message, code: -32603 }, id: data.id }
} }
} }
} }
} else { } else {
const err = `Cannot make ${data.method} request. Remix client is not connected to walletconnect client` const err = `Cannot make ${data.method} request. Remix client is not connected to walletconnect client`
console.error(err) console.error(err)
return {jsonrpc: '2.0', error: { message: err, code: -32603 }, id: data.id} return { jsonrpc: '2.0', error: { message: err, code: -32603 }, id: data.id }
} }
} }

@ -13,7 +13,7 @@ export async function getArtifactsByContractName (contractIdentifier: string) {
const artifact = await fs.readFile(path.join(global.remixContractArtifactsPath, artifactFile), 'utf-8') const artifact = await fs.readFile(path.join(global.remixContractArtifactsPath, artifactFile), 'utf-8')
const artifactJSON: CompilationResult = JSON.parse(artifact) const artifactJSON: CompilationResult = JSON.parse(artifact)
const contractFullPath = (Object.keys(artifactJSON.contracts!)).find((contractName) => artifactJSON.contracts![contractName] && artifactJSON.contracts![contractName][contractIdentifier]) const contractFullPath = (Object.keys(artifactJSON.contracts!)).find((contractName) => artifactJSON.contracts![contractName] && artifactJSON.contracts![contractName][contractIdentifier])
contract = contractFullPath ? artifactJSON.contracts![contractFullPath!][contractIdentifier] : undefined contract = contractFullPath ? artifactJSON.contracts![contractFullPath!][contractIdentifier] : undefined
if (contract) break if (contract) break
} }

@ -2,7 +2,7 @@
import { ethers } from 'ethers' import { ethers } from 'ethers'
import * as hhEtherMethods from './methods' import * as hhEtherMethods from './methods'
for(const method in hhEtherMethods) Object.defineProperty(ethers, method, { value: hhEtherMethods[method]}) for (const method in hhEtherMethods) Object.defineProperty(ethers, method, { value: hhEtherMethods[method] })
export * from 'ethers' export * from 'ethers'
export { ethers } export { ethers }

@ -11,7 +11,7 @@ const providerConfig = {
blockNumber: global.blockNumber || null blockNumber: global.blockNumber || null
} }
const config = { defaultTransactionType: '0x0' } const config = { defaultTransactionType: '0x0' }
global.remixProvider = new Provider(providerConfig) global.remixProvider = new Provider(providerConfig)
global.remixProvider.init() global.remixProvider.init()
global.web3Provider = new ethers.providers.Web3Provider(global.remixProvider) global.web3Provider = new ethers.providers.Web3Provider(global.remixProvider)
@ -194,9 +194,9 @@ const getContractAt = async (contractNameOrABI: ethers.ContractInterface, addres
//@ts-ignore //@ts-ignore
const provider = web3Provider const provider = web3Provider
if(typeof contractNameOrABI === 'string') { if (typeof contractNameOrABI === 'string') {
const result = await getArtifactsByContractName(contractNameOrABI) const result = await getArtifactsByContractName(contractNameOrABI)
if (result) { if (result) {
return new ethers.Contract(address, result.abi, signer || provider.getSigner()) return new ethers.Contract(address, result.abi, signer || provider.getSigner())
} else { } else {

@ -1,4 +1,4 @@
import { default as test} from "tape" import { default as test } from "tape"
import * as common from '../../src/solidity-analyzer/modules/staticAnalysisCommon' import * as common from '../../src/solidity-analyzer/modules/staticAnalysisCommon'
const { localCall, thisLocalCall, libCall, externalDirect, superLocal, assignment, abiNamespaceCallNodes, const { localCall, thisLocalCall, libCall, externalDirect, superLocal, assignment, abiNamespaceCallNodes,
inlineAssembly, unaryOperation, nowAst, blockTimestamp, stateVariableContractNode, inlineAssembly, unaryOperation, nowAst, blockTimestamp, stateVariableContractNode,
@ -6,7 +6,6 @@ const { localCall, thisLocalCall, libCall, externalDirect, superLocal, assignmen
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
lowlevelCall, parameterFunction, parameterFunctionCall, inheritance, blockHashAccess, contractDefinition, funcDefForComplexParams } = require('./astBlocks') lowlevelCall, parameterFunction, parameterFunctionCall, inheritance, blockHashAccess, contractDefinition, funcDefForComplexParams } = require('./astBlocks')
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const compiledContractObj = require('./compilationDetails/CompiledContractObj.json') const compiledContractObj = require('./compilationDetails/CompiledContractObj.json')
function escapeRegExp (str) { function escapeRegExp (str) {
@ -89,7 +88,7 @@ test('staticAnalysisCommon.helpers.operator', function (t) {
test('staticAnalysisCommon.helpers.nodeType', function (t) { test('staticAnalysisCommon.helpers.nodeType', function (t) {
t.plan(3) t.plan(3)
const node = { nodeType: 'Identifier', name: 'now'} const node = { nodeType: 'Identifier', name: 'now' }
const node2 = { nodeType: 'FunctionCall', memberName: 'call' } const node2 = { nodeType: 'FunctionCall', memberName: 'call' }
t.ok(common.helpers.nodeType(node, common.nodeTypes.IDENTIFIER), 'should work for identifier') t.ok(common.helpers.nodeType(node, common.nodeTypes.IDENTIFIER), 'should work for identifier')
@ -140,7 +139,7 @@ test('staticAnalysisCommon.helpers.expressionTypeDescription', function (t) {
test('staticAnalysisCommon.getType', function (t) { test('staticAnalysisCommon.getType', function (t) {
t.plan(3) t.plan(3)
const node = { "argumentTypes": null, const node = { "argumentTypes": null,
"id": 3, "id": 3,
"name": "a", "name": "a",
"nodeType": "Identifier", "nodeType": "Identifier",
@ -357,9 +356,9 @@ test('staticAnalysisCommon.isStateVariable', function (t) {
test('staticAnalysisCommon.isConstantFunction', function (t) { test('staticAnalysisCommon.isConstantFunction', function (t) {
t.plan(3) t.plan(3)
t.ok(common.isConstantFunction(functionDefinition), 'should be const func definition') t.ok(common.isConstantFunction(functionDefinition), 'should be const func definition')
functionDefinition.stateMutability = 'view' functionDefinition.stateMutability = 'view'
t.ok(common.isConstantFunction(functionDefinition), 'should be const func definition') t.ok(common.isConstantFunction(functionDefinition), 'should be const func definition')
functionDefinition.stateMutability = 'nonpayable' functionDefinition.stateMutability = 'nonpayable'
t.notOk(common.isConstantFunction(functionDefinition), 'should not be const func definition') t.notOk(common.isConstantFunction(functionDefinition), 'should not be const func definition')
}) })

@ -46,7 +46,7 @@ test('setup', function (t: test.Test) {
testFiles.forEach((fileName) => { testFiles.forEach((fileName) => {
const content: string = readFileSync(join(__dirname, 'test-contracts/' + folder, fileName), 'utf8') const content: string = readFileSync(join(__dirname, 'test-contracts/' + folder, fileName), 'utf8')
// Latest AST is available under 'compileStandardWrapper' under solc for, 0.4.12 <= version < 0.5.0 // Latest AST is available under 'compileStandardWrapper' under solc for, 0.4.12 <= version < 0.5.0
compilationResults[fileName] = JSON.parse(compiler.compile(compilerInput(content))) compilationResults[fileName] = JSON.parse(compiler.compile(compilerInput(content)))
}) })
@ -820,5 +820,5 @@ function runModuleOnFiles (Module: any, t: test.Test, cb: ((fname: string, repor
t.comment('Error while executing Module: ' + JSON.stringify(report)) t.comment('Error while executing Module: ' + JSON.stringify(report))
} }
cb(fileName, report) cb(fileName, report)
}) })
} }

@ -53,9 +53,6 @@ test('setup', function (t) {
}) })
}); });
test('Integration test thisLocal module', function (t: test.Test) { test('Integration test thisLocal module', function (t: test.Test) {
t.plan(testFiles.length) t.plan(testFiles.length)
const module: any = modules.thisLocal const module: any = modules.thisLocal

@ -29,11 +29,11 @@ test('staticAnalysisIssues.functionParameterPassingError', function (t) {
const res: CompilationResult = compile('functionParameters.sol') const res: CompilationResult = compile('functionParameters.sol')
const Module: any = checksEffectsInteraction const Module: any = checksEffectsInteraction
const statRunner: StatRunner = new StatRunner() const statRunner: StatRunner = new StatRunner()
t.doesNotThrow(() => { t.doesNotThrow(() => {
statRunner.runWithModuleList(res, [{ name: new Module().name, mod: new Module()}]) statRunner.runWithModuleList(res, [{ name: new Module().name, mod: new Module() }])
}, 'Analysis should not throw') }, 'Analysis should not throw')
const reports = statRunner.runWithModuleList(res, [{ name: new Module().name, mod: new Module()}]) const reports = statRunner.runWithModuleList(res, [{ name: new Module().name, mod: new Module() }])
t.ok(!reports.some((mod: AnalysisReport) => mod.report.some((rep: AnalysisReportObj) => rep.warning.includes('INTERNAL ERROR')), 'Should not have internal errors')) t.ok(!reports.some((mod: AnalysisReport) => mod.report.some((rep: AnalysisReportObj) => rep.warning.includes('INTERNAL ERROR')), 'Should not have internal errors'))
}) })

@ -6,7 +6,7 @@ import { default as StatRunner } from '../../src/solidity-analyzer'
import solc from 'solc'; import solc from 'solc';
import { CompilationResult, AnalysisReportObj, AnalysisReport } from '../../src/types' import { CompilationResult, AnalysisReportObj, AnalysisReport } from '../../src/types'
import { checksEffectsInteraction } from '../../src/solidity-analyzer/modules/' import { checksEffectsInteraction } from '../../src/solidity-analyzer/modules/'
const {compilerInput } = helpers.compiler const { compilerInput } = helpers.compiler
const folder: string = 'solidity-v0.5' const folder: string = 'solidity-v0.5'
let compiler let compiler

@ -1,4 +1,4 @@
const node = { "legacyAST": { "children": [{ "attributes": { "literals": ["solidity", ">=", "0.5", ".0", "<", "0.6", ".0"] }, "id": 1, "name": "PragmaDirective", "src": "0:31:0" }, { "attributes": { "SourceUnit": 53, "absolutePath": "mortal.sol", "file": "mortal.sol", "scope": 26, "symbolAliases": [null], "unitAlias": "" }, "id": 2, "name": "ImportDirective", "src": "32:20:0" }, { "attributes": { "contractDependencies": [52], "contractKind": "contract", "documentation": null, "fullyImplemented": true, "linearizedBaseContracts": [25, 52], "name": "Greeter", "scope": 26 }, "children": [{ "attributes": { "arguments": null }, "children": [{ "attributes": { "contractScope": null, "name": "Mortal", "referencedDeclaration": 52, "type": "contract Mortal" }, "id": 3, "name": "UserDefinedTypeName", "src": "74:6:0" }], "id": 4, "name": "InheritanceSpecifier", "src": "74:6:0" }, { "attributes": { "constant": false, "name": "greeting", "scope": 25, "stateVariable": true, "storageLocation": "default", "type": "string", "value": null, "visibility": "internal" }, "children": [{ "attributes": { "name": "string", "type": "string" }, "id": 5, "name": "ElementaryTypeName", "src": "141:6:0" }], "id": 6, "name": "VariableDeclaration", "src": "141:15:0" }, { "attributes": { "documentation": null, "implemented": true, "isConstructor": true, "kind": "constructor", "modifiers": [null], "name": "", "scope": 25, "stateMutability": "nonpayable", "superFunction": null, "visibility": "public" }, "children": [{ "children": [{ "attributes": { "constant": false, "name": "_greeting", "scope": 16, "stateVariable": false, "storageLocation": "memory", "type": "string", "value": null, "visibility": "internal" }, "children": [{ "attributes": { "name": "string", "type": "string" }, "id": 7, "name": "ElementaryTypeName", "src": "225:6:0" }], "id": 8, "name": "VariableDeclaration", "src": "225:23:0" }], "id": 9, "name": "ParameterList", "src": "224:25:0" }, { "attributes": { "parameters": [null] }, "children": [], "id": 10, "name": "ParameterList", "src": "257:0:0" }, { "children": [{ "children": [{ "attributes": { "argumentTypes": null, "isConstant": false, "isLValue": false, "isPure": false, "lValueRequested": false, "operator": "=", "type": "string storage ref" }, "children": [{ "attributes": { "argumentTypes": null, "overloadedDeclarations": [null], "referencedDeclaration": 6, "type": "string storage ref", "value": "greeting" }, "id": 11, "name": "Identifier", "src": "267:8:0" }, { "attributes": { "argumentTypes": null, "overloadedDeclarations": [null], "referencedDeclaration": 8, "type": "string memory", "value": "_greeting" }, "id": 12, "name": "Identifier", "src": "278:9:0" }], "id": 13, "name": "Assignment", "src": "267:20:0" }], "id": 14, "name": "ExpressionStatement", "src": "267:20:0" }], "id": 15, "name": "Block", "src": "257:37:0" }], "id": 16, "name": "FunctionDefinition", "src": "213:81:0" }, { "attributes": { "documentation": null, "implemented": true, "isConstructor": false, "kind": "function", "modifiers": [null], "name": "greet", "scope": 25, "stateMutability": "view", "superFunction": null, "visibility": "public" }, "children": [{ "attributes": { "parameters": [null] }, "children": [], "id": 17, "name": "ParameterList", "src": "338:2:0" }, { "children": [{ "attributes": { "constant": false, "name": "", "scope": 24, "stateVariable": false, "storageLocation": "memory", "type": "string", "value": null, "visibility": "internal" }, "children": [{ "attributes": { "name": "string", "type": "string" }, "id": 18, "name": "ElementaryTypeName", "src": "362:6:0" }], "id": 19, "name": "VariableDeclaration", "src": "362:13:0" }], "id": 20, "name": "ParameterList", "src": "361:15:0" }, { "children": [{ "attributes": { "functionReturnParameters": 20 }, "children": [{ "attributes": { "argumentTypes": null, "overloadedDeclarations": [null], "referencedDeclaration": 6, "type": "string storage ref", "value": "greeting" }, "id": 21, "name": "Identifier", "src": "394:8:0" }], "id": 22, "name": "Return", "src": "387:15:0" }], "id": 23, "name": "Block", "src": "377:32:0" }], "id": 24, "name": "FunctionDefinition", "src": "324:85:0" }], "id": 25, "name": "ContractDefinition", "src": "54:357:0" }], "name": "SourceUnit", "attributes": { "absolutePath": "greeter.sol", "exportedSymbols": { "Greeter": [25] } }, "id": 26, "src": "0:412:0" } } const node = { "legacyAST": { "children": [{ "attributes": { "literals": ["solidity", ">=", "0.5", ".0", "<", "0.6", ".0"]}, "id": 1, "name": "PragmaDirective", "src": "0:31:0" }, { "attributes": { "SourceUnit": 53, "absolutePath": "mortal.sol", "file": "mortal.sol", "scope": 26, "symbolAliases": [null], "unitAlias": "" }, "id": 2, "name": "ImportDirective", "src": "32:20:0" }, { "attributes": { "contractDependencies": [52], "contractKind": "contract", "documentation": null, "fullyImplemented": true, "linearizedBaseContracts": [25, 52], "name": "Greeter", "scope": 26 }, "children": [{ "attributes": { "arguments": null }, "children": [{ "attributes": { "contractScope": null, "name": "Mortal", "referencedDeclaration": 52, "type": "contract Mortal" }, "id": 3, "name": "UserDefinedTypeName", "src": "74:6:0" }], "id": 4, "name": "InheritanceSpecifier", "src": "74:6:0" }, { "attributes": { "constant": false, "name": "greeting", "scope": 25, "stateVariable": true, "storageLocation": "default", "type": "string", "value": null, "visibility": "internal" }, "children": [{ "attributes": { "name": "string", "type": "string" }, "id": 5, "name": "ElementaryTypeName", "src": "141:6:0" }], "id": 6, "name": "VariableDeclaration", "src": "141:15:0" }, { "attributes": { "documentation": null, "implemented": true, "isConstructor": true, "kind": "constructor", "modifiers": [null], "name": "", "scope": 25, "stateMutability": "nonpayable", "superFunction": null, "visibility": "public" }, "children": [{ "children": [{ "attributes": { "constant": false, "name": "_greeting", "scope": 16, "stateVariable": false, "storageLocation": "memory", "type": "string", "value": null, "visibility": "internal" }, "children": [{ "attributes": { "name": "string", "type": "string" }, "id": 7, "name": "ElementaryTypeName", "src": "225:6:0" }], "id": 8, "name": "VariableDeclaration", "src": "225:23:0" }], "id": 9, "name": "ParameterList", "src": "224:25:0" }, { "attributes": { "parameters": [null]}, "children": [], "id": 10, "name": "ParameterList", "src": "257:0:0" }, { "children": [{ "children": [{ "attributes": { "argumentTypes": null, "isConstant": false, "isLValue": false, "isPure": false, "lValueRequested": false, "operator": "=", "type": "string storage ref" }, "children": [{ "attributes": { "argumentTypes": null, "overloadedDeclarations": [null], "referencedDeclaration": 6, "type": "string storage ref", "value": "greeting" }, "id": 11, "name": "Identifier", "src": "267:8:0" }, { "attributes": { "argumentTypes": null, "overloadedDeclarations": [null], "referencedDeclaration": 8, "type": "string memory", "value": "_greeting" }, "id": 12, "name": "Identifier", "src": "278:9:0" }], "id": 13, "name": "Assignment", "src": "267:20:0" }], "id": 14, "name": "ExpressionStatement", "src": "267:20:0" }], "id": 15, "name": "Block", "src": "257:37:0" }], "id": 16, "name": "FunctionDefinition", "src": "213:81:0" }, { "attributes": { "documentation": null, "implemented": true, "isConstructor": false, "kind": "function", "modifiers": [null], "name": "greet", "scope": 25, "stateMutability": "view", "superFunction": null, "visibility": "public" }, "children": [{ "attributes": { "parameters": [null]}, "children": [], "id": 17, "name": "ParameterList", "src": "338:2:0" }, { "children": [{ "attributes": { "constant": false, "name": "", "scope": 24, "stateVariable": false, "storageLocation": "memory", "type": "string", "value": null, "visibility": "internal" }, "children": [{ "attributes": { "name": "string", "type": "string" }, "id": 18, "name": "ElementaryTypeName", "src": "362:6:0" }], "id": 19, "name": "VariableDeclaration", "src": "362:13:0" }], "id": 20, "name": "ParameterList", "src": "361:15:0" }, { "children": [{ "attributes": { "functionReturnParameters": 20 }, "children": [{ "attributes": { "argumentTypes": null, "overloadedDeclarations": [null], "referencedDeclaration": 6, "type": "string storage ref", "value": "greeting" }, "id": 21, "name": "Identifier", "src": "394:8:0" }], "id": 22, "name": "Return", "src": "387:15:0" }], "id": 23, "name": "Block", "src": "377:32:0" }], "id": 24, "name": "FunctionDefinition", "src": "324:85:0" }], "id": 25, "name": "ContractDefinition", "src": "54:357:0" }], "name": "SourceUnit", "attributes": { "absolutePath": "greeter.sol", "exportedSymbols": { "Greeter": [25]} }, "id": 26, "src": "0:412:0" } }
node['source'] = `contract test { node['source'] = `contract test {
int x; int x;

@ -291,7 +291,6 @@ const node: Node = {
} }
} }
node.source = `contract test { node.source = `contract test {
int x; int x;

@ -78,9 +78,9 @@ export class CompilerArtefacts extends Plugin {
saveCompilationPerFileResult(file, source, languageVersion, data) saveCompilationPerFileResult(file, source, languageVersion, data)
}) })
} }
/** /**
* Get artefacts for last compiled contract * Get artefacts for last compiled contract
* * @returns last compiled contract compiler abstract * * @returns last compiled contract compiler abstract
*/ */
getLastCompilationResult () { getLastCompilationResult () {
@ -120,14 +120,14 @@ export class CompilerArtefacts extends Plugin {
/** /**
* Get a particular contract output/artefacts from a compiler output of a Solidity file compilation * Get a particular contract output/artefacts from a compiler output of a Solidity file compilation
* @param compilerOutput compiler output * @param compilerOutput compiler output
* @param contractName contract name * @param contractName contract name
* @returns arefacts object, with fully qualified name (e.g; contracts/1_Storage.sol:Storage) as key * @returns arefacts object, with fully qualified name (e.g; contracts/1_Storage.sol:Storage) as key
*/ */
_getAllContractArtefactsfromOutput (compilerOutput, contractName) { _getAllContractArtefactsfromOutput (compilerOutput, contractName) {
const contractArtefacts = {} const contractArtefacts = {}
for (const filename in compilerOutput) { for (const filename in compilerOutput) {
if(Object.keys(compilerOutput[filename]).includes(contractName)) contractArtefacts[filename + ':' + contractName] = compilerOutput[filename][contractName] if (Object.keys(compilerOutput[filename]).includes(contractName)) contractArtefacts[filename + ':' + contractName] = compilerOutput[filename][contractName]
} }
return contractArtefacts return contractArtefacts
} }
@ -141,10 +141,10 @@ export class CompilerArtefacts extends Plugin {
*/ */
async _populateAllContractArtefactsFromFE (path, contractName, contractArtefacts) { async _populateAllContractArtefactsFromFE (path, contractName, contractArtefacts) {
const dirList = await this.call('fileManager', 'dirList', path) const dirList = await this.call('fileManager', 'dirList', path)
if(dirList && dirList.length) { if (dirList && dirList.length) {
for (const dirPath of dirList) { for (const dirPath of dirList) {
// check if directory contains an 'artifacts' folder and a 'build-info' folder inside 'artifacts' // check if directory contains an 'artifacts' folder and a 'build-info' folder inside 'artifacts'
if(dirPath === path + '/artifacts' && await this.call('fileManager', 'exists', dirPath + '/build-info')) { if (dirPath === path + '/artifacts' && await this.call('fileManager', 'exists', dirPath + '/build-info')) {
const buildFileList = await this.call('fileManager', 'fileList', dirPath + '/build-info') const buildFileList = await this.call('fileManager', 'fileList', dirPath + '/build-info')
// process each build-info file to populate the artefacts for contractName // process each build-info file to populate the artefacts for contractName
for (const buildFile of buildFileList) { for (const buildFile of buildFileList) {
@ -156,13 +156,13 @@ export class CompilerArtefacts extends Plugin {
Object.assign(contractArtefacts, artefacts) Object.assign(contractArtefacts, artefacts)
} }
} else await this._populateAllContractArtefactsFromFE (dirPath, contractName, contractArtefacts) } else await this._populateAllContractArtefactsFromFE (dirPath, contractName, contractArtefacts)
} }
} else return } else return
} }
/** /**
* Get artefacts for a contract (called by script-runner) * Get artefacts for a contract (called by script-runner)
* @param name contract name or fully qualified name i.e. <filename>:<contractname> e.g: contracts/1_Storage.sol:Storage * @param name contract name or fully qualified name i.e. <filename>:<contractname> e.g: contracts/1_Storage.sol:Storage
* @returns artefacts for the contract * @returns artefacts for the contract
*/ */
async getArtefactsByContractName (name) { async getArtefactsByContractName (name) {
@ -173,12 +173,12 @@ export class CompilerArtefacts extends Plugin {
const nameArr = fullyQualifiedName.split(':') const nameArr = fullyQualifiedName.split(':')
const filename = nameArr[0] const filename = nameArr[0]
const contract = nameArr[1] const contract = nameArr[1]
if(Object.keys(contractsDataByFilename).includes(filename) && contractsDataByFilename[filename][contract]) if (Object.keys(contractsDataByFilename).includes(filename) && contractsDataByFilename[filename][contract])
return contractsDataByFilename[filename][contract] return contractsDataByFilename[filename][contract]
else { else {
const allContractsData = {} const allContractsData = {}
await this._populateAllContractArtefactsFromFE ('contracts', contract, allContractsData) await this._populateAllContractArtefactsFromFE ('contracts', contract, allContractsData)
if(allContractsData[fullyQualifiedName]) return { fullyQualifiedName, artefact: allContractsData[fullyQualifiedName]} if (allContractsData[fullyQualifiedName]) return { fullyQualifiedName, artefact: allContractsData[fullyQualifiedName] }
else throw new Error(`Could not find artifacts for ${fullyQualifiedName}. Compile contract to generate artifacts.`) else throw new Error(`Could not find artifacts for ${fullyQualifiedName}. Compile contract to generate artifacts.`)
} }
} else { } else {

@ -44,7 +44,7 @@ export class CompilerImports extends Plugin {
return {} return {}
} }
}) })
} }
onActivation(): void { onActivation(): void {
@ -155,7 +155,7 @@ export class CompilerImports extends Plugin {
if (targetPath && this.currentRequest) { if (targetPath && this.currentRequest) {
const canCall = await this.askUserPermission('resolveAndSave', 'This action will update the path ' + targetPath) const canCall = await this.askUserPermission('resolveAndSave', 'This action will update the path ' + targetPath)
if (!canCall) throw new Error('No permission to update ' + targetPath) if (!canCall) throw new Error('No permission to update ' + targetPath)
} }
const provider = await this.call('fileManager', 'getProviderOf', url) const provider = await this.call('fileManager', 'getProviderOf', url)
if (provider) { if (provider) {
if (provider.type === 'localhost' && !provider.isConnected()) { if (provider.type === 'localhost' && !provider.isConnected()) {

@ -155,7 +155,7 @@ export class FetchAndCompile extends Plugin {
this.call('notification', 'toast', e.message) this.call('notification', 'toast', e.message)
setTimeout(_ => this.emit('notFound', contractAddress), 0) // plugin framework returns a time out error although it actually didn't find the source... setTimeout(_ => this.emit('notFound', contractAddress), 0) // plugin framework returns a time out error although it actually didn't find the source...
this.unresolvedAddresses.push(contractAddress) this.unresolvedAddresses.push(contractAddress)
return localCompilation() return localCompilation()
} }
} }
@ -176,7 +176,7 @@ export class FetchAndCompile extends Plugin {
} }
} }
const { settings, compilationTargets } = data const { settings, compilationTargets } = data
try { try {
setTimeout(_ => this.emit('compiling', settings), 0) setTimeout(_ => this.emit('compiling', settings), 0)
const compData = await compile( const compData = await compile(

@ -78,19 +78,19 @@ export class CompilerMetadata extends Plugin {
solcLongVersion, solcLongVersion,
input input
}) })
const id = createHash('md5').update(Buffer.from(json)).digest().toString('hex') const id = createHash('md5').update(Buffer.from(json)).digest().toString('hex')
const buildFilename = this.joinPath(path, this.innerPath, 'build-info/' + id + '.json') const buildFilename = this.joinPath(path, this.innerPath, 'build-info/' + id + '.json')
// If there are no file in buildInfoNames,it means compilation is running first time after loading Remix // If there are no file in buildInfoNames,it means compilation is running first time after loading Remix
if (!this.buildInfoNames[filePath]) { if (!this.buildInfoNames[filePath]) {
// Check the existing build-info and delete all the previous build files for compiled file // Check the existing build-info and delete all the previous build files for compiled file
await this.removeStoredBuildInfo(input, path, filePath) await this.removeStoredBuildInfo(input, path, filePath)
this.buildInfoNames[filePath] = buildFilename this.buildInfoNames[filePath] = buildFilename
const buildData = {id, _format: format, solcVersion, solcLongVersion, input, output} const buildData = { id, _format: format, solcVersion, solcLongVersion, input, output }
await this.call('fileManager', 'writeFile', buildFilename, JSON.stringify(buildData, null, '\t')) await this.call('fileManager', 'writeFile', buildFilename, JSON.stringify(buildData, null, '\t'))
} else if (this.buildInfoNames[filePath] && this.buildInfoNames[filePath] !== buildFilename) { } else if (this.buildInfoNames[filePath] && this.buildInfoNames[filePath] !== buildFilename) {
await this.call('fileManager', 'remove', this.buildInfoNames[filePath]) await this.call('fileManager', 'remove', this.buildInfoNames[filePath])
this.buildInfoNames[filePath] = buildFilename this.buildInfoNames[filePath] = buildFilename
const buildData = {id, _format: format, solcVersion, solcLongVersion, input, output} const buildData = { id, _format: format, solcVersion, solcLongVersion, input, output }
await this.call('fileManager', 'writeFile', buildFilename, JSON.stringify(buildData, null, '\t')) await this.call('fileManager', 'writeFile', buildFilename, JSON.stringify(buildData, null, '\t'))
} }
} }
@ -136,7 +136,7 @@ export class CompilerMetadata extends Plugin {
}, },
abi: contract.object.abi abi: contract.object.abi
} }
await this.call('fileManager', 'writeFile', fileName, JSON.stringify(data, null, '\t')) await this.call('fileManager', 'writeFile', fileName, JSON.stringify(data, null, '\t'))
this.emit('artefactsUpdated', fileName, contract) this.emit('artefactsUpdated', fileName, contract)
} }

@ -140,7 +140,6 @@ export const UUPSupgradeAbi = {
"type": "function" "type": "function"
} }
export const UUPSupgradeToAndCallAbi = { export const UUPSupgradeToAndCallAbi = {
"inputs": [ "inputs": [
{ {

@ -117,7 +117,7 @@ export class GistHandler extends Plugin {
const gistIdWorkspace = 'gist ' + gistId const gistIdWorkspace = 'gist ' + gistId
const workspaces = await this.call('filePanel', 'getWorkspaces') const workspaces = await this.call('filePanel', 'getWorkspaces')
const found = workspaces.find((workspace) => workspace.name === gistIdWorkspace) const found = workspaces.find((workspace) => workspace.name === gistIdWorkspace)
if (found) { if (found) {
await this.call('notification', 'alert', { await this.call('notification', 'alert', {
id: 'gistAlert', id: 'gistAlert',
message: `workspace "${gistIdWorkspace}" already exists`, message: `workspace "${gistIdWorkspace}" already exists`,

@ -88,7 +88,7 @@ export class OpenZeppelinProxy extends Plugin {
} }
async deployUUPSProxy(implAddress: string, _data: string, implementationContractObject): Promise<void> { async deployUUPSProxy(implAddress: string, _data: string, implementationContractObject): Promise<void> {
const args = [implAddress, _data] const args = [implAddress, _data]
const constructorData = await this.blockchain.getEncodedParams(args, UUPSfunAbi) const constructorData = await this.blockchain.getEncodedParams(args, UUPSfunAbi)
const proxyName = 'ERC1967Proxy' const proxyName = 'ERC1967Proxy'
@ -109,7 +109,7 @@ export class OpenZeppelinProxy extends Plugin {
data.dataHex = UUPSBytecode + constructorData.replace('0x', '') data.dataHex = UUPSBytecode + constructorData.replace('0x', '')
data.funAbi = UUPSfunAbi data.funAbi = UUPSfunAbi
this.call('terminal', 'logHtml', `Deploying ERC1967 < 5.0.0 as proxy...`) this.call('terminal', 'logHtml', `Deploying ERC1967 < 5.0.0 as proxy...`)
}else{ } else {
this.call('terminal', 'logHtml', `Deploying ERC1967 >= 5.0.0 as proxy...`) this.call('terminal', 'logHtml', `Deploying ERC1967 >= 5.0.0 as proxy...`)
} }
// re-use implementation contract's ABI for UI display in udapp and change name to proxy name. // re-use implementation contract's ABI for UI display in udapp and change name to proxy name.

@ -44,10 +44,10 @@ export class Ethdebugger {
this.event = new EventManager() this.event = new EventManager()
this.traceManager = new TraceManager({ web3: this.web3 }) this.traceManager = new TraceManager({ web3: this.web3 })
this.codeManager = new CodeManager(this.traceManager) this.codeManager = new CodeManager(this.traceManager)
this.solidityProxy = new SolidityProxy({ this.solidityProxy = new SolidityProxy({
getCurrentCalledAddressAt: this.traceManager.getCurrentCalledAddressAt.bind(this.traceManager), getCurrentCalledAddressAt: this.traceManager.getCurrentCalledAddressAt.bind(this.traceManager),
getCode: this.codeManager.getCode.bind(this.codeManager), getCode: this.codeManager.getCode.bind(this.codeManager),
compilationResult: this.compilationResult compilationResult: this.compilationResult
}) })
this.storageResolver = null this.storageResolver = null
@ -63,8 +63,8 @@ export class Ethdebugger {
setManagers () { setManagers () {
this.traceManager = new TraceManager({ web3: this.web3 }) this.traceManager = new TraceManager({ web3: this.web3 })
this.codeManager = new CodeManager(this.traceManager) this.codeManager = new CodeManager(this.traceManager)
this.solidityProxy = new SolidityProxy({ this.solidityProxy = new SolidityProxy({
getCurrentCalledAddressAt: this.traceManager.getCurrentCalledAddressAt.bind(this.traceManager), getCurrentCalledAddressAt: this.traceManager.getCurrentCalledAddressAt.bind(this.traceManager),
getCode: this.codeManager.getCode.bind(this.codeManager), getCode: this.codeManager.getCode.bind(this.codeManager),
compilationResult: this.compilationResult compilationResult: this.compilationResult
}) })

@ -110,7 +110,7 @@ export class VmDebuggerLogic {
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} }
try { try {
const memory = this._traceManager.getMemoryAt(index) const memory = this._traceManager.getMemoryAt(index)
if (this.stepManager.currentStepIndex === index) { if (this.stepManager.currentStepIndex === index) {
@ -122,9 +122,9 @@ export class VmDebuggerLogic {
try { try {
const address = this._traceManager.getCurrentCalledAddressAt(index) const address = this._traceManager.getCurrentCalledAddressAt(index)
if (!this.storageResolver) return if (!this.storageResolver) return
const storageViewer = new StorageViewer({ stepIndex: this.stepManager.currentStepIndex, tx: this.tx, address: address }, this.storageResolver, this._traceManager) const storageViewer = new StorageViewer({ stepIndex: this.stepManager.currentStepIndex, tx: this.tx, address: address }, this.storageResolver, this._traceManager)
storageViewer.storageRange().then((storage) => { storageViewer.storageRange().then((storage) => {
if (this.stepManager.currentStepIndex === index) { if (this.stepManager.currentStepIndex === index) {
const header = storageViewer.isComplete(address) ? '[Completely Loaded]' : '[Partially Loaded]' const header = storageViewer.isComplete(address) ? '[Completely Loaded]' : '[Partially Loaded]'
@ -145,8 +145,8 @@ export class VmDebuggerLogic {
} catch (error) { } catch (error) {
this.event.trigger('traceReturnValueUpdate', [[error]]) this.event.trigger('traceReturnValueUpdate', [[error]])
} }
})() })()
}, 1000) }, 1000)
try { try {
const step = this._traceManager.getCurrentStep(index) const step = this._traceManager.getCurrentStep(index)

@ -84,10 +84,10 @@ export class Debugger {
const generatedSources = this.debugger.callTree.sourceLocationTracker.getGeneratedSourcesFromAddress(address) const generatedSources = this.debugger.callTree.sourceLocationTracker.getGeneratedSourcesFromAddress(address)
const lineColumnPos = rawLocationAndOpcode.lineColumnPos const lineColumnPos = rawLocationAndOpcode.lineColumnPos
let lineGasCostObj = null let lineGasCostObj = null
try { try {
lineGasCostObj = await this.debugger.callTree.getGasCostPerLine(rawLocation.file, lineColumnPos.start.line) lineGasCostObj = await this.debugger.callTree.getGasCostPerLine(rawLocation.file, lineColumnPos.start.line)
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} }
@ -97,9 +97,9 @@ export class Debugger {
const instructionIndexes = lineGasCostObj.indexes.map((index) => { // translate from vmtrace index to instruction index const instructionIndexes = lineGasCostObj.indexes.map((index) => { // translate from vmtrace index to instruction index
return this.debugger.codeManager.getInstructionIndex(address, index) return this.debugger.codeManager.getInstructionIndex(address, index)
}) })
this.vmDebuggerLogic.event.trigger('lineGasCostChanged', [instructionIndexes, lineColumnPos.start.line ]) this.vmDebuggerLogic.event.trigger('lineGasCostChanged', [instructionIndexes, lineColumnPos.start.line])
this.currentFile = rawLocation.file this.currentFile = rawLocation.file
this.currentLine = lineColumnPos.start.line this.currentLine = lineColumnPos.start.line
} }
} else { } else {
this.event.trigger('newSourceLocation', [null]) this.event.trigger('newSourceLocation', [null])

@ -32,7 +32,7 @@ export class DebuggerSolidityState {
} }
if (this.stepManager.currentStepIndex !== index) return if (this.stepManager.currentStepIndex !== index) return
if (!this.storageResolver) { if (!this.storageResolver) {
return return
} }

@ -77,7 +77,7 @@ export class DebuggerStepManager {
const revertedReason = this.currentCall.outofgas ? 'outofgas' : 'reverted' const revertedReason = this.currentCall.outofgas ? 'outofgas' : 'reverted'
this.revertionPoint = this.currentCall.return this.revertionPoint = this.currentCall.return
this.event.trigger('revertWarning', [revertedReason]) this.event.trigger('revertWarning', [revertedReason])
return return
} }
for (let k = callsPath.length - 2; k >= 0; k--) { for (let k = callsPath.length - 2; k >= 0; k--) {
const parent = callsPath[k] const parent = callsPath[k]

@ -1,9 +1,9 @@
'use strict' 'use strict'
import Web3, { Web3PluginBase } from 'web3' import Web3, { Web3PluginBase } from 'web3'
import {toNumber} from 'web3-utils' import { toNumber } from 'web3-utils'
export function extendWeb3 (web3) { export function extendWeb3 (web3) {
if(!web3.debug){ if (!web3.debug){
web3.registerPlugin(new Web3DebugPlugin()) web3.registerPlugin(new Web3DebugPlugin())
} }
} }

@ -97,7 +97,7 @@ export class InternalCallTree {
}) })
} catch (e) { } catch (e) {
console.log(e) console.log(e)
} }
} }
}) })
} }
@ -214,7 +214,7 @@ export class InternalCallTree {
} }
throw new Error('Could not find gas cost per line') throw new Error('Could not find gas cost per line')
} }
getLocalVariableById (id: number) { getLocalVariableById (id: number) {
return this.variables[id] return this.variables[id]
} }
@ -226,7 +226,7 @@ async function buildTree (tree, step, scopeId, isCreation, functionDefinition?,
const address = tree.traceManager.getCurrentCalledAddressAt(step) const address = tree.traceManager.getCurrentCalledAddressAt(step)
await registerFunctionParameters(tree, functionDefinition, step, scopeId, contractObj, validSourceLocation, address) await registerFunctionParameters(tree, functionDefinition, step, scopeId, contractObj, validSourceLocation, address)
} }
function callDepthChange (step, trace) { function callDepthChange (step, trace) {
if (step + 1 < trace.length) { if (step + 1 < trace.length) {
return trace[step].depth !== trace[step + 1].depth return trace[step].depth !== trace[step + 1].depth
@ -252,11 +252,11 @@ async function buildTree (tree, step, scopeId, isCreation, functionDefinition?,
let sourceLocation let sourceLocation
let validSourceLocation let validSourceLocation
let address let address
try { try {
address = tree.traceManager.getCurrentCalledAddressAt(step) address = tree.traceManager.getCurrentCalledAddressAt(step)
sourceLocation = await tree.extractSourceLocation(step, address) sourceLocation = await tree.extractSourceLocation(step, address)
if (!includedSource(sourceLocation, currentSourceLocation)) { if (!includedSource(sourceLocation, currentSourceLocation)) {
tree.reducedTrace.push(step) tree.reducedTrace.push(step)
currentSourceLocation = sourceLocation currentSourceLocation = sourceLocation
@ -270,7 +270,7 @@ async function buildTree (tree, step, scopeId, isCreation, functionDefinition?,
validSourceLocation = previousValidSourceLocation validSourceLocation = previousValidSourceLocation
} else } else
validSourceLocation = currentSourceLocation validSourceLocation = currentSourceLocation
} catch (e) { } catch (e) {
return { outStep: step, error: 'InternalCallTree - Error resolving source location. ' + step + ' ' + e } return { outStep: step, error: 'InternalCallTree - Error resolving source location. ' + step + ' ' + e }
} }
@ -285,7 +285,7 @@ async function buildTree (tree, step, scopeId, isCreation, functionDefinition?,
} else { } else {
stepDetail.gasCost = parseInt(stepDetail.gasCost as unknown as string) stepDetail.gasCost = parseInt(stepDetail.gasCost as unknown as string)
} }
// gas per line // gas per line
let lineColumnPos let lineColumnPos
if (tree.offsetToLineColumnConverter) { if (tree.offsetToLineColumnConverter) {
@ -299,7 +299,7 @@ async function buildTree (tree, step, scopeId, isCreation, functionDefinition?,
sources[genSource.name] = { content: genSource.contents } sources[genSource.name] = { content: genSource.contents }
} }
} }
lineColumnPos = await tree.offsetToLineColumnConverter.offsetToLineColumn(validSourceLocation, validSourceLocation.file, sources, astSources) lineColumnPos = await tree.offsetToLineColumnConverter.offsetToLineColumn(validSourceLocation, validSourceLocation.file, sources, astSources)
if (!tree.gasCostPerLine[validSourceLocation.file]) tree.gasCostPerLine[validSourceLocation.file] = {} if (!tree.gasCostPerLine[validSourceLocation.file]) tree.gasCostPerLine[validSourceLocation.file] = {}
if (!tree.gasCostPerLine[validSourceLocation.file][lineColumnPos.start.line]) { if (!tree.gasCostPerLine[validSourceLocation.file][lineColumnPos.start.line]) {
@ -391,7 +391,7 @@ function getGeneratedSources (tree, scopeId, contractObj) {
async function registerFunctionParameters (tree, functionDefinition, step, scopeId, contractObj, sourceLocation, address) { async function registerFunctionParameters (tree, functionDefinition, step, scopeId, contractObj, sourceLocation, address) {
tree.functionCallStack.push(step) tree.functionCallStack.push(step)
const functionDefinitionAndInputs = { functionDefinition, inputs: [] } const functionDefinitionAndInputs = { functionDefinition, inputs: []}
// means: the previous location was a function definition && JUMPDEST // means: the previous location was a function definition && JUMPDEST
// => we are at the beginning of the function and input/output are setup // => we are at the beginning of the function and input/output are setup
try { try {

@ -64,7 +64,7 @@ export class SolidityProxy {
*/ */
async extractStatesDefinitions (address: string) { async extractStatesDefinitions (address: string) {
const compilationResult = await this.compilationResult(address) const compilationResult = await this.compilationResult(address)
if (!this.cache.contractDeclarations[address]) { if (!this.cache.contractDeclarations[address]) {
this.cache.contractDeclarations[address] = extractContractDefinitions(compilationResult.data.sources) this.cache.contractDeclarations[address] = extractContractDefinitions(compilationResult.data.sources)
} }
if (!this.cache.statesDefinitions[address]) { if (!this.cache.statesDefinitions[address]) {

@ -1,5 +1,5 @@
'use strict' 'use strict'
import { util } from '@remix-project/remix-lib' import { util } from '@remix-project/remix-lib'
import { bytesToHex } from '@ethereumjs/util' import { bytesToHex } from '@ethereumjs/util'
const { toHexPaddedString } = util const { toHexPaddedString } = util
import * as traceHelper from './traceHelper' import * as traceHelper from './traceHelper'

@ -155,7 +155,7 @@ export class TraceManager {
return stack.map(el => toHexPaddedString(el)) return stack.map(el => toHexPaddedString(el))
} else { } else {
// it's an object coming from the VM. // it's an object coming from the VM.
// for performance reasons, // for performance reasons,
// we don't turn the stack coming from the VM into an array when the tx is executed // we don't turn the stack coming from the VM into an array when the tx is executed
// but now when the app needs it. // but now when the app needs it.
const stack = [] const stack = []

@ -37,7 +37,7 @@ const compilationData = JSON.parse(solc.compileStandardWrapper(JSON.stringify(in
console.dir(Object.keys(compilationData)) console.dir(Object.keys(compilationData))
const compilation = {} const compilation = {}
compilation['data'] = compilationData compilation['data'] = compilationData
compilation['source'] = {sources: inputJson.sources} compilation['source'] = { sources: inputJson.sources }
console.dir(compilation) console.dir(compilation)
console.dir(compilation['data'].errors) console.dir(compilation['data'].errors)

@ -5,7 +5,7 @@ import { CodeManager } from '../src/code/codeManager'
const web3Test = require('./resources/testWeb3.ts') const web3Test = require('./resources/testWeb3.ts')
tape('CodeManager', function (t) { tape('CodeManager', function (t) {
const traceManager = new TraceManager({web3: web3Test}) const traceManager = new TraceManager({ web3: web3Test })
const codeManager = new CodeManager(traceManager) const codeManager = new CodeManager(traceManager)
const contractCode = web3Test.eth.getCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5') const contractCode = web3Test.eth.getCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5')
codeManager.codeResolver.cacheExecutingCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', contractCode) // so a call to web3 is not necessary codeManager.codeResolver.cacheExecutingCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', contractCode) // so a call to web3 is not necessary

@ -156,7 +156,7 @@ contract Ballot {
output = JSON.parse(output) output = JSON.parse(output)
const param = '0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000148656c6c6f20576f726c64210000000000000000000000000000000000000000' const param = '0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000148656c6c6f20576f726c64210000000000000000000000000000000000000000'
const web3 = await vmCall.getWeb3() const web3 = await vmCall.getWeb3()
vmCall.sendTx(web3, {nonce: 0, privateKey: privateKey}, undefined, 0, output.contracts['test.sol']['Ballot'].evm.bytecode.object + param, (error, hash) => { vmCall.sendTx(web3, { nonce: 0, privateKey: privateKey }, undefined, 0, output.contracts['test.sol']['Ballot'].evm.bytecode.object + param, (error, hash) => {
console.log(error, hash) console.log(error, hash)
if (error) { if (error) {
throw error throw error
@ -177,7 +177,7 @@ contract Ballot {
} }
} }
}) })
debugManager.callTree.event.register('callTreeReady', () => { debugManager.callTree.event.register('callTreeReady', () => {
testDebugging(debugManager) testDebugging(debugManager)
}) })
@ -189,7 +189,7 @@ contract Ballot {
console.error(error) console.error(error)
throw error throw error
}) })
debugManager.debug(tx) debugManager.debug(tx)
}) })
.catch(error => { throw error }) .catch(error => { throw error })
@ -279,10 +279,10 @@ function testDebugging (debugManager) {
tape('breakPointManager', (t) => { tape('breakPointManager', (t) => {
t.plan(2) t.plan(2)
const {traceManager, callTree, solidityProxy} = debugManager const { traceManager, callTree, solidityProxy } = debugManager
const breakPointManager = new BreakpointManager({traceManager, callTree, solidityProxy}) const breakPointManager = new BreakpointManager({ traceManager, callTree, solidityProxy })
breakPointManager.add({fileName: 'test.sol', row: 39}) breakPointManager.add({ fileName: 'test.sol', row: 39 })
breakPointManager.event.register('breakpointHit', function (sourceLocation, step) { breakPointManager.event.register('breakpointHit', function (sourceLocation, step) {
t.equal(JSON.stringify(sourceLocation), JSON.stringify({ start: 1146, length: 6, file: 0, jump: '-' })) t.equal(JSON.stringify(sourceLocation), JSON.stringify({ start: 1146, length: 6, file: 0, jump: '-' }))

@ -11,4 +11,4 @@ module.exports = {
uint p = 45; uint p = 45;
} }
} }
`} ` }

@ -39,4 +39,4 @@ contract intLocal {
uint8 ui81 = asd; uint8 ui81 = asd;
} }
} }
`} ` }

@ -36,4 +36,4 @@ contract miscLocal {
string memory smallstring = "test_test_test"; string memory smallstring = "test_test_test";
} }
} }
`} ` }

@ -81,4 +81,4 @@ contract structArrayLocal {
arrayStruct.c = enumdef.three; arrayStruct.c = enumdef.three;
} }
} }
`} ` }

@ -31,7 +31,7 @@ async function test (st, privateKey) {
let compilationResults = new CompilerAbstract('json', output, sources) let compilationResults = new CompilerAbstract('json', output, sources)
console.log('intLocalTest') console.log('intLocalTest')
await intLocalTest(st, privateKey, output.contracts['test.sol']['intLocal'].evm.bytecode.object, compilationResults, intLocal.contract) await intLocalTest(st, privateKey, output.contracts['test.sol']['intLocal'].evm.bytecode.object, compilationResults, intLocal.contract)
output = compiler.compile(compilerInput(miscLocal.contract)) output = compiler.compile(compilerInput(miscLocal.contract))
output = JSON.parse(output) output = JSON.parse(output)
sources = { sources = {
@ -41,7 +41,7 @@ async function test (st, privateKey) {
compilationResults = new CompilerAbstract('json', output, sources) compilationResults = new CompilerAbstract('json', output, sources)
console.log('miscLocalTest') console.log('miscLocalTest')
await miscLocalTest(st, privateKey, output.contracts['test.sol']['miscLocal'].evm.bytecode.object, compilationResults, miscLocal.contract) await miscLocalTest(st, privateKey, output.contracts['test.sol']['miscLocal'].evm.bytecode.object, compilationResults, miscLocal.contract)
output = compiler.compile(compilerInput(miscLocal.contract)) output = compiler.compile(compilerInput(miscLocal.contract))
output = JSON.parse(output) output = JSON.parse(output)
sources = { sources = {
@ -51,7 +51,7 @@ async function test (st, privateKey) {
compilationResults = new CompilerAbstract('json', output, sources) compilationResults = new CompilerAbstract('json', output, sources)
console.log('misc2LocalTest') console.log('misc2LocalTest')
await misc2LocalTest(st, privateKey, output.contracts['test.sol']['miscLocal2'].evm.bytecode.object, compilationResults, miscLocal.contract) await misc2LocalTest(st, privateKey, output.contracts['test.sol']['miscLocal2'].evm.bytecode.object, compilationResults, miscLocal.contract)
output = compiler.compile(compilerInput(structArrayLocal.contract)) output = compiler.compile(compilerInput(structArrayLocal.contract))
output = JSON.parse(output) output = JSON.parse(output)
sources = { sources = {

@ -30,8 +30,8 @@ module.exports = async function (st, privateKey, contractBytecode, compilationRe
const traceManager = new TraceManager({ web3 }) const traceManager = new TraceManager({ web3 })
const codeManager = new CodeManager(traceManager) const codeManager = new CodeManager(traceManager)
codeManager.clear() codeManager.clear()
const solidityProxy = new SolidityProxy({ const solidityProxy = new SolidityProxy({
getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager), getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager),
getCode: codeManager.getCode.bind(codeManager), getCode: codeManager.getCode.bind(codeManager),
compilationResult: () => compilationResult compilationResult: () => compilationResult
}) })
@ -54,7 +54,7 @@ module.exports = async function (st, privateKey, contractBytecode, compilationRe
callTree.event.register('callTreeReady', (scopes, scopeStarts) => { callTree.event.register('callTreeReady', (scopes, scopeStarts) => {
helper.decodeLocals(st, 140, traceManager, callTree, function (locals) { helper.decodeLocals(st, 140, traceManager, callTree, function (locals) {
try { try {
const expected = {"p":{"value":"45","type":"uint256"},"foo":{"length":"1","value":[{"value":"3","type":"uint8"}],"type":"uint8[1]"},"boo":{"length":"1","value":[{"length":"2","value":[{"value":"R","type":"string"},{"value":"T","type":"string"}],"type":"string[2]"}],"type":"string[2][1]"}} const expected = { "p":{ "value":"45","type":"uint256" },"foo":{ "length":"1","value":[{ "value":"3","type":"uint8" }],"type":"uint8[1]" },"boo":{ "length":"1","value":[{ "length":"2","value":[{ "value":"R","type":"string" },{ "value":"T","type":"string" }],"type":"string[2]" }],"type":"string[2][1]" } }
st.deepEqual(locals, expected) st.deepEqual(locals, expected)
} catch (e) { } catch (e) {
st.fail(e.message) st.fail(e.message)
@ -62,7 +62,6 @@ module.exports = async function (st, privateKey, contractBytecode, compilationRe
resolve({}) resolve({})
}) })
}) })
traceManager.resolveTrace(tx).then(() => { traceManager.resolveTrace(tx).then(() => {
debuggerEvent.trigger('newTraceLoaded', [traceManager.trace]) debuggerEvent.trigger('newTraceLoaded', [traceManager.trace])

@ -12,9 +12,9 @@ import * as helper from './helper'
module.exports = function (st, privateKey, contractBytecode, compilationResult, contractCode) { module.exports = function (st, privateKey, contractBytecode, compilationResult, contractCode) {
// eslint-disable-next-line no-async-promise-executor // eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve) => { return new Promise(async (resolve) => {
const web3 = await (vmCall as any).getWeb3(); const web3 = await (vmCall as any).getWeb3();
(vmCall as any).sendTx(web3, { nonce: 0, privateKey: privateKey }, undefined, 0, contractBytecode, function (error, hash) { (vmCall as any).sendTx(web3, { nonce: 0, privateKey: privateKey }, undefined, 0, contractBytecode, function (error, hash) {
if (error) { if (error) {
return st.fail(error) return st.fail(error)
} }
@ -24,10 +24,10 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
const traceManager = new TraceManager({ web3 }) const traceManager = new TraceManager({ web3 })
const codeManager = new CodeManager(traceManager) const codeManager = new CodeManager(traceManager)
codeManager.clear() codeManager.clear()
const solidityProxy = new SolidityProxy({ const solidityProxy = new SolidityProxy({
getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager), getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager),
getCode: codeManager.getCode.bind(codeManager), getCode: codeManager.getCode.bind(codeManager),
compilationResult: () => compilationResult compilationResult: () => compilationResult
}) })
const debuggerEvent = new EventManager() const debuggerEvent = new EventManager()
const offsetToLineColumnConverter = { const offsetToLineColumnConverter = {
@ -47,26 +47,26 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
}) })
callTree.event.register('callTreeReady', async (scopes, scopeStarts) => { callTree.event.register('callTreeReady', async (scopes, scopeStarts) => {
try { try {
// test gas cost per line // test gas cost per line
st.equals((await callTree.getGasCostPerLine(0, 16)).gasCost, 11) st.equals((await callTree.getGasCostPerLine(0, 16)).gasCost, 11)
st.equals((await callTree.getGasCostPerLine(0, 32)).gasCost, 84) st.equals((await callTree.getGasCostPerLine(0, 32)).gasCost, 84)
const functions1 = callTree.retrieveFunctionsStack(103) const functions1 = callTree.retrieveFunctionsStack(103)
const functions2 = callTree.retrieveFunctionsStack(116) const functions2 = callTree.retrieveFunctionsStack(116)
const functions3 = callTree.retrieveFunctionsStack(13) const functions3 = callTree.retrieveFunctionsStack(13)
st.equals(functions1.length, 2) st.equals(functions1.length, 2)
st.equals(functions2.length, 3) st.equals(functions2.length, 3)
st.equals(functions3.length, 1) st.equals(functions3.length, 1)
st.equal(functions1[0].gasCost, 54) st.equal(functions1[0].gasCost, 54)
st.equal(functions1[1].gasCost, 436) st.equal(functions1[1].gasCost, 436)
st.equal(functions2[0].gasCost, 23) st.equal(functions2[0].gasCost, 23)
st.equal(functions2[1].gasCost, 54) st.equal(functions2[1].gasCost, 54)
st.equal(functions2[2].gasCost, 436) st.equal(functions2[2].gasCost, 436)
st.equals(Object.keys(functions1[0])[0], 'functionDefinition') st.equals(Object.keys(functions1[0])[0], 'functionDefinition')
st.equals(Object.keys(functions1[0])[1], 'inputs') st.equals(Object.keys(functions1[0])[1], 'inputs')
st.equals(functions1[0].inputs[0], 'foo') st.equals(functions1[0].inputs[0], 'foo')
@ -76,11 +76,11 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
st.equals(Object.keys(functions2[1])[1], 'inputs') st.equals(Object.keys(functions2[1])[1], 'inputs')
st.equals(functions2[0].inputs[0], 'asd') st.equals(functions2[0].inputs[0], 'asd')
st.equals(functions2[1].inputs[0], 'foo') st.equals(functions2[1].inputs[0], 'foo')
st.equals(functions1[0].functionDefinition.name, 'level11') st.equals(functions1[0].functionDefinition.name, 'level11')
st.equals(functions2[0].functionDefinition.name, 'level12') st.equals(functions2[0].functionDefinition.name, 'level12')
st.equals(functions2[1].functionDefinition.name, 'level11') st.equals(functions2[1].functionDefinition.name, 'level11')
st.equals(scopeStarts[0], '1') st.equals(scopeStarts[0], '1')
st.equals(scopeStarts[10], '1.1') st.equals(scopeStarts[10], '1.1')
st.equals(scopeStarts[102], '1.1.1') st.equals(scopeStarts[102], '1.1.1')
@ -111,7 +111,7 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
} catch (e) { } catch (e) {
st.fail(e.message) st.fail(e.message)
} }
helper.decodeLocals(st, 95, traceManager, callTree, function (locals) { helper.decodeLocals(st, 95, traceManager, callTree, function (locals) {
st.equals(Object.keys(locals).length, 16) st.equals(Object.keys(locals).length, 16)
st.equals(locals['ui8'].value, '130') st.equals(locals['ui8'].value, '130')
@ -130,7 +130,7 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
st.equals(locals['i'].value, '-32432423423') st.equals(locals['i'].value, '-32432423423')
st.equals(locals['ishrink'].value, '2') st.equals(locals['ishrink'].value, '2')
}) })
helper.decodeLocals(st, 106, traceManager, callTree, function (locals) { helper.decodeLocals(st, 106, traceManager, callTree, function (locals) {
try { try {
st.equals(locals['ui8'].value, '123') st.equals(locals['ui8'].value, '123')

@ -13,7 +13,7 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
// eslint-disable-next-line no-async-promise-executor // eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve) => { return new Promise(async (resolve) => {
const web3 = await (vmCall as any).getWeb3(); const web3 = await (vmCall as any).getWeb3();
(vmCall as any).sendTx(web3, { nonce: 0, privateKey: privateKey }, undefined, 0, contractBytecode, function (error, hash) { (vmCall as any).sendTx(web3, { nonce: 0, privateKey: privateKey }, undefined, 0, contractBytecode, function (error, hash) {
if (error) { if (error) {
return st.fail(error) return st.fail(error)
} }
@ -23,10 +23,10 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
const traceManager = new TraceManager({ web3 }) const traceManager = new TraceManager({ web3 })
const codeManager = new CodeManager(traceManager) const codeManager = new CodeManager(traceManager)
codeManager.clear() codeManager.clear()
const solidityProxy = new SolidityProxy({ const solidityProxy = new SolidityProxy({
getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager), getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager),
getCode: codeManager.getCode.bind(codeManager), getCode: codeManager.getCode.bind(codeManager),
compilationResult: () => compilationResult compilationResult: () => compilationResult
}) })
const debuggerEvent = new EventManager() const debuggerEvent = new EventManager()
const offsetToLineColumnConverter = { const offsetToLineColumnConverter = {
@ -65,7 +65,7 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
st.fail(e.message) st.fail(e.message)
} }
}) })
helper.decodeLocals(st, 7, traceManager, callTree, function (locals) { helper.decodeLocals(st, 7, traceManager, callTree, function (locals) {
try { try {
// st.equals(Object.keys(locals).length, 0) // st.equals(Object.keys(locals).length, 0)
@ -84,5 +84,5 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
}) })
.catch(error => st.fail(error)) .catch(error => st.fail(error))
}) })
}) })
} }

@ -23,10 +23,10 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
const traceManager = new TraceManager({ web3 }) const traceManager = new TraceManager({ web3 })
const codeManager = new CodeManager(traceManager) const codeManager = new CodeManager(traceManager)
codeManager.clear() codeManager.clear()
const solidityProxy = new SolidityProxy({ const solidityProxy = new SolidityProxy({
getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager), getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager),
getCode: codeManager.getCode.bind(codeManager), getCode: codeManager.getCode.bind(codeManager),
compilationResult: () => compilationResult compilationResult: () => compilationResult
}) })
const debuggerEvent = new EventManager() const debuggerEvent = new EventManager()
const offsetToLineColumnConverter = { const offsetToLineColumnConverter = {
@ -51,7 +51,7 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
st.fail(e.message) st.fail(e.message)
} }
}) })
helper.decodeLocals(st, 7, traceManager, callTree, function (locals) { helper.decodeLocals(st, 7, traceManager, callTree, function (locals) {
try { try {
// st.equals(Object.keys(locals).length, 0) // st.equals(Object.keys(locals).length, 0)
@ -70,5 +70,5 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,
}) })
.catch(error => st.fail(error)) .catch(error => st.fail(error))
}) })
}) })
} }

@ -23,10 +23,10 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,c
const traceManager = new TraceManager({ web3 }) const traceManager = new TraceManager({ web3 })
const codeManager = new CodeManager(traceManager) const codeManager = new CodeManager(traceManager)
codeManager.clear() codeManager.clear()
const solidityProxy = new SolidityProxy({ const solidityProxy = new SolidityProxy({
getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager), getCurrentCalledAddressAt: traceManager.getCurrentCalledAddressAt.bind(traceManager),
getCode: codeManager.getCode.bind(codeManager), getCode: codeManager.getCode.bind(codeManager),
compilationResult: () => compilationResult compilationResult: () => compilationResult
}) })
const debuggerEvent = new EventManager() const debuggerEvent = new EventManager()
const offsetToLineColumnConverter = { const offsetToLineColumnConverter = {
@ -59,24 +59,24 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,c
st.equals(locals['f'].raw, '0x746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f') st.equals(locals['f'].raw, '0x746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f746573745f6c6f6e675f')
st.equals(locals['f'].value, 'test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_') st.equals(locals['f'].value, 'test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_test_long_')
st.equals(locals['e'].value['e'].value, true) st.equals(locals['e'].value['e'].value, true)
st.equals(locals['simpleArray'].value[0].value, '45') st.equals(locals['simpleArray'].value[0].value, '45')
st.equals(locals['simpleArray'].value[1].value, '324324') st.equals(locals['simpleArray'].value[1].value, '324324')
st.equals(locals['simpleArray'].value[2].value, '-333') st.equals(locals['simpleArray'].value[2].value, '-333')
st.equals(locals['simpleArray'].value[3].value, '5656') st.equals(locals['simpleArray'].value[3].value, '5656')
st.equals(locals['simpleArray'].value[4].value, '-1111') st.equals(locals['simpleArray'].value[4].value, '-1111')
st.equals(locals['stringArray'].value[0].value, 'long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_') st.equals(locals['stringArray'].value[0].value, 'long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_long_one_')
st.equals(locals['stringArray'].value[1].value, 'two') st.equals(locals['stringArray'].value[1].value, 'two')
st.equals(locals['stringArray'].value[2].value, 'three') st.equals(locals['stringArray'].value[2].value, 'three')
st.equals(locals['dynArray'].value[0].value[0].value, '3423423532') st.equals(locals['dynArray'].value[0].value[0].value, '3423423532')
st.equals(locals['dynArray'].value[1].value[0].value, '-342343323532') st.equals(locals['dynArray'].value[1].value[0].value, '-342343323532')
st.equals(locals['dynArray'].value[1].value[1].value, '23432') st.equals(locals['dynArray'].value[1].value[1].value, '23432')
st.equals(locals['dynArray'].value[2].value[0].value, '-432432') st.equals(locals['dynArray'].value[2].value[0].value, '-432432')
st.equals(locals['dynArray'].value[2].value[1].value, '3423423532') st.equals(locals['dynArray'].value[2].value[1].value, '3423423532')
st.equals(locals['dynArray'].value[2].value[2].value, '-432432') st.equals(locals['dynArray'].value[2].value[2].value, '-432432')
st.equals(locals['structArray'].value[0].value['a'].value, 'test') st.equals(locals['structArray'].value[0].value['a'].value, 'test')
st.equals(locals['structArray'].value[0].value['a'].length, '0x8') st.equals(locals['structArray'].value[0].value['a'].length, '0x8')
st.equals(locals['structArray'].value[0].value['a'].raw, '0x74657374') st.equals(locals['structArray'].value[0].value['a'].raw, '0x74657374')
@ -86,31 +86,31 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,c
st.equals(locals['structArray'].value[0].value['c'].value, 'test_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_test') st.equals(locals['structArray'].value[0].value['c'].value, 'test_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_testtest_long_test_long_test_long_test')
st.equals(locals['structArray'].value[0].value['d'].value, '3') st.equals(locals['structArray'].value[0].value['d'].value, '3')
st.equals(locals['structArray'].value[0].value['e'].value, true) st.equals(locals['structArray'].value[0].value['e'].value, true)
st.equals(locals['structArray'].value[1].value['a'].value, 'item1 a') st.equals(locals['structArray'].value[1].value['a'].value, 'item1 a')
st.equals(locals['structArray'].value[1].value['b'].value, '20') st.equals(locals['structArray'].value[1].value['b'].value, '20')
st.equals(locals['structArray'].value[1].value['c'].value, 'item1 c') st.equals(locals['structArray'].value[1].value['c'].value, 'item1 c')
st.equals(locals['structArray'].value[1].value['d'].value, '-45') st.equals(locals['structArray'].value[1].value['d'].value, '-45')
st.equals(locals['structArray'].value[1].value['e'].value, false) st.equals(locals['structArray'].value[1].value['e'].value, false)
st.equals(locals['structArray'].value[2].value['a'].value, 'item2 a') st.equals(locals['structArray'].value[2].value['a'].value, 'item2 a')
st.equals(locals['structArray'].value[2].value['b'].value, '200') st.equals(locals['structArray'].value[2].value['b'].value, '200')
st.equals(locals['structArray'].value[2].value['c'].value, 'item2 c') st.equals(locals['structArray'].value[2].value['c'].value, 'item2 c')
st.equals(locals['structArray'].value[2].value['d'].value, '-450') st.equals(locals['structArray'].value[2].value['d'].value, '-450')
st.equals(locals['structArray'].value[2].value['e'].value, true) st.equals(locals['structArray'].value[2].value['e'].value, true)
st.equals(locals['arrayStruct'].value.a.value[0].value, 'string') st.equals(locals['arrayStruct'].value.a.value[0].value, 'string')
st.equals(locals['arrayStruct'].value.b.value[0].value, '34') st.equals(locals['arrayStruct'].value.b.value[0].value, '34')
st.equals(locals['arrayStruct'].value.b.value[1].value, '-23') st.equals(locals['arrayStruct'].value.b.value[1].value, '-23')
st.equals(locals['arrayStruct'].value.b.value[2].value, '-3') st.equals(locals['arrayStruct'].value.b.value[2].value, '-3')
st.equals(locals['arrayStruct'].value.c.value, 'three') st.equals(locals['arrayStruct'].value.c.value, 'three')
st.equals(Object.keys(locals).length, 8) st.equals(Object.keys(locals).length, 8)
} catch (e) { } catch (e) {
st.fail(e.message) st.fail(e.message)
} }
}) })
helper.decodeLocals(st, 7, traceManager, callTree, function (locals) { helper.decodeLocals(st, 7, traceManager, callTree, function (locals) {
try { try {
console.log('at 7', locals) console.log('at 7', locals)
@ -130,5 +130,5 @@ module.exports = function (st, privateKey, contractBytecode, compilationResult,c
}) })
.catch(error => st.fail(error)) .catch(error => st.fail(error))
}) })
}) })
} }

@ -10,7 +10,7 @@ import { InternalCallTree } from '../../../src/solidity-decoder/internalCallTree
import * as vmCall from '../../vmCall' import * as vmCall from '../../vmCall'
import { StorageResolver } from '../../../src/storage/storageResolver' import { StorageResolver } from '../../../src/storage/storageResolver'
import { StorageViewer } from '../../../src/storage/storageViewer' import { StorageViewer } from '../../../src/storage/storageViewer'
import { Address, bytesToHex } from '@ethereumjs/util' import { Address, bytesToHex } from '@ethereumjs/util'
module.exports = async function testMappingStorage (st, cb) { module.exports = async function testMappingStorage (st, cb) {
const mappingStorage = require('../contracts/mappingStorage') const mappingStorage = require('../contracts/mappingStorage')
@ -23,7 +23,7 @@ module.exports = async function testMappingStorage (st, cb) {
} }
const compilationResults = new CompilerAbstract('json', output, sources) const compilationResults = new CompilerAbstract('json', output, sources)
const web3 = await (vmCall as any).getWeb3(); const web3 = await (vmCall as any).getWeb3();
(vmCall as any).sendTx(web3, {nonce: 0, privateKey: privateKey}, undefined, 0, output.contracts['test.sol']['SimpleMappingState'].evm.bytecode.object, function (error, hash) { (vmCall as any).sendTx(web3, { nonce: 0, privateKey: privateKey }, undefined, 0, output.contracts['test.sol']['SimpleMappingState'].evm.bytecode.object, function (error, hash) {
if (error) { if (error) {
console.log(error) console.log(error)
st.end(error) st.end(error)
@ -44,7 +44,7 @@ module.exports = async function testMappingStorage (st, cb) {
} }
function testMapping (st, privateKey, contractAddress, output, compilationResults, web3, cb) { function testMapping (st, privateKey, contractAddress, output, compilationResults, web3, cb) {
(vmCall as any).sendTx(web3, {nonce: 1, privateKey: privateKey}, contractAddress, 0, '2fd0a83a00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001074686973206973206120737472696e6700000000000000000000000000000000', (vmCall as any).sendTx(web3, { nonce: 1, privateKey: privateKey }, contractAddress, 0, '2fd0a83a00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001074686973206973206120737472696e6700000000000000000000000000000000',
function (error, hash) { function (error, hash) {
if (error) { if (error) {
console.log(error) console.log(error)
@ -74,7 +74,7 @@ function testMapping (st, privateKey, contractAddress, output, compilationResult
stepIndex: 268, stepIndex: 268,
tx: tx, tx: tx,
address: contractAddress address: contractAddress
}, new StorageResolver({web3}), traceManager) }, new StorageResolver({ web3 }), traceManager)
const stateVars = stateDecoder.extractStateVariables('SimpleMappingState', output.sources) const stateVars = stateDecoder.extractStateVariables('SimpleMappingState', output.sources)
stateDecoder.decodeState(stateVars, storageViewer).then((result) => { stateDecoder.decodeState(stateVars, storageViewer).then((result) => {
st.equal(result['_num'].value, '1') st.equal(result['_num'].value, '1')

@ -13,8 +13,8 @@ export function compilerInput (contracts) {
}, },
outputSelection: { outputSelection: {
'*': { '*': {
'': [ 'ast' ], '': ['ast'],
'*': [ 'abi', 'metadata', 'evm.legacyAssembly', 'evm.bytecode', 'evm.deployedBytecode', 'evm.methodIdentifiers', 'evm.gasEstimates' ] '*': ['abi', 'metadata', 'evm.legacyAssembly', 'evm.bytecode', 'evm.deployedBytecode', 'evm.methodIdentifiers', 'evm.gasEstimates']
} }
} }
} }

@ -1,14 +1,14 @@
const node = {} const node = {}
node['ast'] = {"legacyAST":{"children":[{"attributes":{"fullyImplemented":true,"isLibrary":false,"linearizedBaseContracts":[5640396],"name":"test"},"children":[{"attributes":{"name":"x","type":"int256"},"children":[{"attributes":{"name":"int"},"id":5657860,"name":"ElementaryTypeName","src":"21:3:11"}],"id":5658100,"name":"VariableDeclaration","src":"21:5:11"},{"attributes":{"name":"y","type":"int256"},"children":[{"attributes":{"name":"int"},"id":5658180,"name":"ElementaryTypeName","src":"38:3:11"}],"id":5658268,"name":"VariableDeclaration","src":"38:5:11"},{"attributes":{"constant":false,"name":"set","public":true},"children":[{"children":[{"attributes":{"name":"_x","type":"int256"},"children":[{"attributes":{"name":"int"},"id":5658404,"name":"ElementaryTypeName","src":"68:3:11"}],"id":5658492,"name":"VariableDeclaration","src":"68:6:11"}],"id":5658572,"name":"ParameterList","src":"67:8:11"},{"children":[{"attributes":{"name":"_r","type":"int256"},"children":[{"attributes":{"name":"int"},"id":5658628,"name":"ElementaryTypeName","src":"85:3:11"}],"id":5658716,"name":"VariableDeclaration","src":"85:6:11"}],"id":5658796,"name":"ParameterList","src":"84:8:11"},{"children":[{"children":[{"attributes":{"operator":"=","type":"int256"},"children":[{"attributes":{"type":"int256","value":"x"},"id":5658900,"name":"Identifier","src":"108:1:11"},{"attributes":{"type":"int256","value":"_x"},"id":5658980,"name":"Identifier","src":"112:2:11"}],"id":5657492,"name":"Assignment","src":"108:6:11"}],"id":5659028,"name":"ExpressionStatement","src":"108:6:11"},{"children":[{"attributes":{"operator":"=","type":"int256"},"children":[{"attributes":{"type":"int256","value":"y"},"id":5659116,"name":"Identifier","src":"125:1:11"},{"attributes":{"string":null,"type":"int_const 10","value":"10"},"id":5659196,"name":"Literal","src":"129:2:11"}],"id":5659252,"name":"Assignment","src":"125:6:11"}],"id":5659316,"name":"ExpressionStatement","src":"125:6:11"},{"children":[{"attributes":{"operator":"=","type":"int256"},"children":[{"attributes":{"type":"int256","value":"_r"},"id":5659428,"name":"Identifier","src":"141:2:11"},{"attributes":{"type":"int256","value":"x"},"id":5639308,"name":"Identifier","src":"146:1:11"}],"id":5639356,"name":"Assignment","src":"141:6:11"}],"id":5639420,"name":"ExpressionStatement","src":"141:6:11"}],"id":5639516,"name":"Block","src":"97:57:11"}],"id":5639612,"name":"FunctionDefinition","src":"55:99:11"},{"attributes":{"constant":false,"name":"get","public":true},"children":[{"children":[],"id":5639764,"name":"ParameterList","src":"179:2:11"},{"children":[{"attributes":{"name":"x","type":"uint256"},"children":[{"attributes":{"name":"uint"},"id":5639820,"name":"ElementaryTypeName","src":"191:4:11"}],"id":5639908,"name":"VariableDeclaration","src":"191:6:11"},{"attributes":{"name":"y","type":"uint256"},"children":[{"attributes":{"name":"uint"},"id":5639988,"name":"ElementaryTypeName","src":"199:4:11"}],"id":5640076,"name":"VariableDeclaration","src":"199:6:11"}],"id":5640156,"name":"ParameterList","src":"190:16:11"},{"children":[],"id":5640212,"name":"Block","src":"212:17:11"}],"id":5640276,"name":"FunctionDefinition","src":"167:62:11"}],"id":5640396,"name":"ContractDefinition","src":"0:231:11"}],"name":"SourceUnit"}} node['ast'] = { "legacyAST":{ "children":[{ "attributes":{ "fullyImplemented":true,"isLibrary":false,"linearizedBaseContracts":[5640396],"name":"test" },"children":[{ "attributes":{ "name":"x","type":"int256" },"children":[{ "attributes":{ "name":"int" },"id":5657860,"name":"ElementaryTypeName","src":"21:3:11" }],"id":5658100,"name":"VariableDeclaration","src":"21:5:11" },{ "attributes":{ "name":"y","type":"int256" },"children":[{ "attributes":{ "name":"int" },"id":5658180,"name":"ElementaryTypeName","src":"38:3:11" }],"id":5658268,"name":"VariableDeclaration","src":"38:5:11" },{ "attributes":{ "constant":false,"name":"set","public":true },"children":[{ "children":[{ "attributes":{ "name":"_x","type":"int256" },"children":[{ "attributes":{ "name":"int" },"id":5658404,"name":"ElementaryTypeName","src":"68:3:11" }],"id":5658492,"name":"VariableDeclaration","src":"68:6:11" }],"id":5658572,"name":"ParameterList","src":"67:8:11" },{ "children":[{ "attributes":{ "name":"_r","type":"int256" },"children":[{ "attributes":{ "name":"int" },"id":5658628,"name":"ElementaryTypeName","src":"85:3:11" }],"id":5658716,"name":"VariableDeclaration","src":"85:6:11" }],"id":5658796,"name":"ParameterList","src":"84:8:11" },{ "children":[{ "children":[{ "attributes":{ "operator":"=","type":"int256" },"children":[{ "attributes":{ "type":"int256","value":"x" },"id":5658900,"name":"Identifier","src":"108:1:11" },{ "attributes":{ "type":"int256","value":"_x" },"id":5658980,"name":"Identifier","src":"112:2:11" }],"id":5657492,"name":"Assignment","src":"108:6:11" }],"id":5659028,"name":"ExpressionStatement","src":"108:6:11" },{ "children":[{ "attributes":{ "operator":"=","type":"int256" },"children":[{ "attributes":{ "type":"int256","value":"y" },"id":5659116,"name":"Identifier","src":"125:1:11" },{ "attributes":{ "string":null,"type":"int_const 10","value":"10" },"id":5659196,"name":"Literal","src":"129:2:11" }],"id":5659252,"name":"Assignment","src":"125:6:11" }],"id":5659316,"name":"ExpressionStatement","src":"125:6:11" },{ "children":[{ "attributes":{ "operator":"=","type":"int256" },"children":[{ "attributes":{ "type":"int256","value":"_r" },"id":5659428,"name":"Identifier","src":"141:2:11" },{ "attributes":{ "type":"int256","value":"x" },"id":5639308,"name":"Identifier","src":"146:1:11" }],"id":5639356,"name":"Assignment","src":"141:6:11" }],"id":5639420,"name":"ExpressionStatement","src":"141:6:11" }],"id":5639516,"name":"Block","src":"97:57:11" }],"id":5639612,"name":"FunctionDefinition","src":"55:99:11" },{ "attributes":{ "constant":false,"name":"get","public":true },"children":[{ "children":[],"id":5639764,"name":"ParameterList","src":"179:2:11" },{ "children":[{ "attributes":{ "name":"x","type":"uint256" },"children":[{ "attributes":{ "name":"uint" },"id":5639820,"name":"ElementaryTypeName","src":"191:4:11" }],"id":5639908,"name":"VariableDeclaration","src":"191:6:11" },{ "attributes":{ "name":"y","type":"uint256" },"children":[{ "attributes":{ "name":"uint" },"id":5639988,"name":"ElementaryTypeName","src":"199:4:11" }],"id":5640076,"name":"VariableDeclaration","src":"199:6:11" }],"id":5640156,"name":"ParameterList","src":"190:16:11" },{ "children":[],"id":5640212,"name":"Block","src":"212:17:11" }],"id":5640276,"name":"FunctionDefinition","src":"167:62:11" }],"id":5640396,"name":"ContractDefinition","src":"0:231:11" }],"name":"SourceUnit" } }
node['ast'].ast = { node['ast'].ast = {
absolutePath: 'sample.sol', absolutePath: 'sample.sol',
exportedSymbols: { test: [ 33 ] }, exportedSymbols: { test: [33]},
id: 34, id: 34,
nodeType: 'SourceUnit', nodeType: 'SourceUnit',
nodes: nodes:
[ { [{
abstract: false, abstract: false,
baseContracts: [], baseContracts: [],
contractDependencies: [], contractDependencies: [],
@ -16,11 +16,11 @@ node['ast'].ast = {
documentation: null, documentation: null,
fullyImplemented: true, fullyImplemented: true,
id: 33, id: 33,
linearizedBaseContracts: [ 33 ], linearizedBaseContracts: [33],
name: 'test', name: 'test',
nodeType: 'ContractDefinition', nodeType: 'ContractDefinition',
nodes: nodes:
[ { constant: false, [{ constant: false,
id: 2, id: 2,
name: 'x', name: 'x',
nodeType: 'VariableDeclaration', nodeType: 'VariableDeclaration',
@ -30,12 +30,12 @@ node['ast'].ast = {
stateVariable: true, stateVariable: true,
storageLocation: 'default', storageLocation: 'default',
typeDescriptions: { typeIdentifier: 't_int256', typeString: 'int256' }, typeDescriptions: { typeIdentifier: 't_int256', typeString: 'int256' },
typeName: { typeName: {
id: 1, id: 1,
name: 'int', name: 'int',
nodeType: 'ElementaryTypeName', nodeType: 'ElementaryTypeName',
src: '20:3:0', src: '20:3:0',
typeDescriptions: [Object] typeDescriptions: [Object]
}, },
value: null, value: null,
visibility: 'internal' }, visibility: 'internal' },
@ -54,14 +54,14 @@ node['ast'].ast = {
name: 'int', name: 'int',
nodeType: 'ElementaryTypeName', nodeType: 'ElementaryTypeName',
src: '31:3:0', src: '31:3:0',
typeDescriptions: [Object] }, typeDescriptions: [Object]},
value: null, value: null,
visibility: 'internal' }, visibility: 'internal' },
{ body: { id: 23, { body: { id: 23,
nodeType: 'Block', nodeType: 'Block',
src: '96:55:0', src: '96:55:0',
statements: statements:
[ { expression: [{ expression:
{ argumentTypes: null, { argumentTypes: null,
id: 13, id: 13,
isConstant: false, isConstant: false,
@ -69,7 +69,7 @@ node['ast'].ast = {
isPure: false, isPure: false,
lValueRequested: false, lValueRequested: false,
leftHandSide: leftHandSide:
{ argumentTypes: null, { argumentTypes: null,
id: 11, id: 11,
name: 'x', name: 'x',
nodeType: 'Identifier', nodeType: 'Identifier',
@ -89,7 +89,7 @@ node['ast'].ast = {
src: '110:2:0', src: '110:2:0',
typeDescriptions: { typeIdentifier: 't_int256', typeString: 'int256' } }, typeDescriptions: { typeIdentifier: 't_int256', typeString: 'int256' } },
src: '106:6:0', src: '106:6:0',
typeDescriptions: { typeIdentifier: 't_int256', typeString: 'int256' } typeDescriptions: { typeIdentifier: 't_int256', typeString: 'int256' }
}, },
id: 14, id: 14,
nodeType: 'ExpressionStatement', nodeType: 'ExpressionStatement',
@ -106,7 +106,7 @@ node['ast'].ast = {
operator: '=', operator: '=',
rightHandSide: [Object], rightHandSide: [Object],
src: '122:6:0', src: '122:6:0',
typeDescriptions: [Object] }, typeDescriptions: [Object]},
id: 18, id: 18,
nodeType: 'ExpressionStatement', nodeType: 'ExpressionStatement',
src: '122:6:0' }, src: '122:6:0' },
@ -122,10 +122,10 @@ node['ast'].ast = {
operator: '=', operator: '=',
rightHandSide: [Object], rightHandSide: [Object],
src: '138:6:0', src: '138:6:0',
typeDescriptions: [Object] }, typeDescriptions: [Object]},
id: 22, id: 22,
nodeType: 'ExpressionStatement', nodeType: 'ExpressionStatement',
src: '138:6:0' } ] src: '138:6:0' }]
}, },
documentation: null, documentation: null,
functionSelector: 'e5c19b2d', functionSelector: 'e5c19b2d',
@ -149,7 +149,7 @@ node['ast'].ast = {
stateMutability: 'nonpayable', stateMutability: 'nonpayable',
virtual: false, virtual: false,
visibility: 'public' }, visibility: 'public' },
{ body: { id: 31, nodeType: 'Block', src: '214:17:0', statements: [] }, { body: { id: 31, nodeType: 'Block', src: '214:17:0', statements: []},
documentation: null, documentation: null,
functionSelector: '6d4ce63c', functionSelector: '6d4ce63c',
id: 32, id: 32,
@ -173,13 +173,12 @@ node['ast'].ast = {
src: '163:68:0', src: '163:68:0',
stateMutability: 'nonpayable', stateMutability: 'nonpayable',
virtual: false, virtual: false,
visibility: 'public' } ], visibility: 'public' }],
scope: 34, scope: 34,
src: '0:233:0' src: '0:233:0'
} ], }],
src: '0:233:0' src: '0:233:0'
} }
node['source'] = `contract test { node['source'] = `contract test {
int x; int x;

@ -7,7 +7,7 @@ let data = init.readFile(require('path').resolve(__dirname, 'testWeb3.json'), nu
data = JSON.parse(data) data = JSON.parse(data)
let traceWithABIEncoder = init.readFile(require('path').resolve(__dirname, 'traceWithABIEncoder.json'), null) let traceWithABIEncoder = init.readFile(require('path').resolve(__dirname, 'traceWithABIEncoder.json'), null)
traceWithABIEncoder = traceWithABIEncoder =
data.testTraces['0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd53'] = JSON.parse(traceWithABIEncoder) data.testTraces['0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd53'] = JSON.parse(traceWithABIEncoder)
web3Override.eth.getCode = function (address, callback) { web3Override.eth.getCode = function (address, callback) {
@ -48,7 +48,7 @@ web3Override.eth.setProvider = function (provider) {}
web3Override.eth.providers = { 'HttpProvider': function (url) {} } web3Override.eth.providers = { 'HttpProvider': function (url) {} }
web3Override.eth.currentProvider = {'host': 'test provider'} web3Override.eth.currentProvider = { 'host': 'test provider' }
if (typeof (module) !== 'undefined' && typeof (module.exports) !== 'undefined') { if (typeof (module) !== 'undefined' && typeof (module.exports) !== 'undefined') {
module.exports = web3Override module.exports = web3Override

@ -11,20 +11,20 @@ import { compilerInput } from './helpers/compilerHelper'
tape('SourceLocationTracker', function (t) { tape('SourceLocationTracker', function (t) {
t.test('SourceLocationTracker.getSourceLocationFromVMTraceIndex - simple contract', async function (st) { t.test('SourceLocationTracker.getSourceLocationFromVMTraceIndex - simple contract', async function (st) {
const traceManager = new TraceManager({web3: web3Test}) const traceManager = new TraceManager({ web3: web3Test })
const codeManager = new CodeManager(traceManager) const codeManager = new CodeManager(traceManager)
let output = compiler.compile(compilerInput(contracts)) let output = compiler.compile(compilerInput(contracts))
output = JSON.parse(output) output = JSON.parse(output)
codeManager.codeResolver.cacheExecutingCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', '0x' + output.contracts['test.sol']['test'].evm.deployedBytecode.object) codeManager.codeResolver.cacheExecutingCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', '0x' + output.contracts['test.sol']['test'].evm.deployedBytecode.object)
const tx = web3Test.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd52') const tx = web3Test.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd52')
traceManager.resolveTrace(tx).then(async () => { traceManager.resolveTrace(tx).then(async () => {
const sourceLocationTracker = new SourceLocationTracker(codeManager, { debugWithGeneratedSources: false })
const sourceLocationTracker = new SourceLocationTracker(codeManager, {debugWithGeneratedSources: false})
try { try {
const map = await sourceLocationTracker.getSourceLocationFromVMTraceIndex('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', 0, output.contracts) const map = await sourceLocationTracker.getSourceLocationFromVMTraceIndex('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', 0, output.contracts)
st.equal(map['file'], 0) st.equal(map['file'], 0)
@ -42,20 +42,18 @@ tape('SourceLocationTracker', function (t) {
t.test('SourceLocationTracker.getSourceLocationFromVMTraceIndex - ABIEncoder V2 contract', async function (st) { t.test('SourceLocationTracker.getSourceLocationFromVMTraceIndex - ABIEncoder V2 contract', async function (st) {
const traceManager = new TraceManager({web3: web3Test}) const traceManager = new TraceManager({ web3: web3Test })
const codeManager = new CodeManager(traceManager) const codeManager = new CodeManager(traceManager)
let output = compiler.compile(compilerInput(ABIEncoderV2)) let output = compiler.compile(compilerInput(ABIEncoderV2))
output = JSON.parse(output) output = JSON.parse(output)
codeManager.codeResolver.cacheExecutingCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', '0x' + output.contracts['test.sol']['test'].evm.deployedBytecode.object) codeManager.codeResolver.cacheExecutingCode('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', '0x' + output.contracts['test.sol']['test'].evm.deployedBytecode.object)
const tx = web3Test.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd53') const tx = web3Test.eth.getTransaction('0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd53')
traceManager.resolveTrace(tx).then(async () => { traceManager.resolveTrace(tx).then(async () => {
try { try {
// with debugWithGeneratedSources: false // with debugWithGeneratedSources: false
const sourceLocationTracker = new SourceLocationTracker(codeManager, { debugWithGeneratedSources: false }) const sourceLocationTracker = new SourceLocationTracker(codeManager, { debugWithGeneratedSources: false })
@ -67,7 +65,7 @@ tape('SourceLocationTracker', function (t) {
map = await sourceLocationTracker.getSourceLocationFromVMTraceIndex('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', 45, output.contracts) map = await sourceLocationTracker.getSourceLocationFromVMTraceIndex('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', 45, output.contracts)
st.equal(map['file'], 1) // 1 refers to the generated source (pragma experimental ABIEncoderV2) st.equal(map['file'], 1) // 1 refers to the generated source (pragma experimental ABIEncoderV2)
map = await sourceLocationTracker.getValidSourceLocationFromVMTraceIndex('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', 45, output.contracts) map = await sourceLocationTracker.getValidSourceLocationFromVMTraceIndex('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', 45, output.contracts)
st.equal(map['file'], 0) // 1 refers to the generated source (pragma experimental ABIEncoderV2) st.equal(map['file'], 0) // 1 refers to the generated source (pragma experimental ABIEncoderV2)
st.equal(map['start'], 303) st.equal(map['start'], 303)
@ -84,7 +82,7 @@ tape('SourceLocationTracker', function (t) {
try { try {
// with debugWithGeneratedSources: true // with debugWithGeneratedSources: true
const sourceLocationTracker = new SourceLocationTracker(codeManager, { debugWithGeneratedSources: true }) const sourceLocationTracker = new SourceLocationTracker(codeManager, { debugWithGeneratedSources: true })
let map = await sourceLocationTracker.getSourceLocationFromVMTraceIndex('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', 0, output.contracts) let map = await sourceLocationTracker.getSourceLocationFromVMTraceIndex('0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', 0, output.contracts)
console.log(map) console.log(map)
st.equal(map['file'], 0) st.equal(map['file'], 0)

@ -7,7 +7,7 @@ tape('TraceManager', function (t) {
let traceManager let traceManager
t.test('TraceManager.init', function (st) { t.test('TraceManager.init', function (st) {
traceManager = new TraceManager({web3: web3Test}) traceManager = new TraceManager({ web3: web3Test })
st.end() st.end()
}) })

@ -1,10 +1,9 @@
'use strict' 'use strict'
import { extendWeb3 } from '../src/init' import { extendWeb3 } from '../src/init'
import { Address } from '@ethereumjs/util' import { Address } from '@ethereumjs/util'
import { Web3 } from 'web3'; import { Web3 } from 'web3';
const { Provider } = require('@remix-project/remix-simulator') const { Provider } = require('@remix-project/remix-simulator')
async function getWeb3 () { async function getWeb3 () {
const remixSimulatorProvider = new Provider({ fork: 'berlin' }) const remixSimulatorProvider = new Provider({ fork: 'berlin' })
await remixSimulatorProvider.init() await remixSimulatorProvider.init()

@ -1,11 +1,11 @@
import { util } from '@remix-project/remix-lib' import { util } from '@remix-project/remix-lib'
const { toHexPaddedString, formatMemory } = util const { toHexPaddedString, formatMemory } = util
import { helpers } from '@remix-project/remix-lib' import { helpers } from '@remix-project/remix-lib'
const { normalizeHexAddress } = helpers.ui const { normalizeHexAddress } = helpers.ui
import { ConsoleLogs, hash } from '@remix-project/remix-lib' import { ConsoleLogs, hash } from '@remix-project/remix-lib'
import { toChecksumAddress, bytesToHex, Address, toBytes, bigIntToHex} from '@ethereumjs/util' import { toChecksumAddress, bytesToHex, Address, toBytes, bigIntToHex } from '@ethereumjs/util'
import utils, {toBigInt} from 'web3-utils' import utils, { toBigInt } from 'web3-utils'
import {isBigInt} from 'web3-validator' import { isBigInt } from 'web3-validator'
import { ethers } from 'ethers' import { ethers } from 'ethers'
import { VMContext } from './vm-context' import { VMContext } from './vm-context'
import type { EVMStateManagerInterface } from '@ethereumjs/common' import type { EVMStateManagerInterface } from '@ethereumjs/common'
@ -99,7 +99,7 @@ export class VmProxy {
setVM (vm) { setVM (vm) {
if (this.vm === vm) return if (this.vm === vm) return
this.vm = vm this.vm = vm
this.vm.evm.events.on('step', async (data: InterpreterStep, resolve: (result?: any) => void) => { this.vm.evm.events.on('step', async (data: InterpreterStep, resolve: (result?: any) => void) => {
await this.pushTrace(data) await this.pushTrace(data)
resolve() resolve()
}) })
@ -110,7 +110,7 @@ export class VmProxy {
}) })
this.vm.events.on('beforeTx', async (data: TypedTransaction, resolve: (result?: any) => void) => { this.vm.events.on('beforeTx', async (data: TypedTransaction, resolve: (result?: any) => void) => {
this.txRunning = true this.txRunning = true
await this.txWillProcess(data) await this.txWillProcess(data)
resolve() resolve()
}) })
} }
@ -124,7 +124,7 @@ export class VmProxy {
recordVMSteps (record) { recordVMSteps (record) {
this.flagrecordVMSteps = record this.flagrecordVMSteps = record
} }
async txWillProcess (data: TypedTransaction) { async txWillProcess (data: TypedTransaction) {
if (!this.flagrecordVMSteps) return if (!this.flagrecordVMSteps) return
this.lastMemoryUpdate = [] this.lastMemoryUpdate = []
@ -234,7 +234,7 @@ export class VmProxy {
async pushTrace (data: InterpreterStep) { async pushTrace (data: InterpreterStep) {
if (!this.flagrecordVMSteps) return if (!this.flagrecordVMSteps) return
try { try {
const depth = data.depth + 1 // geth starts the depth from 1 const depth = data.depth + 1 // geth starts the depth from 1
if (!this.processingHash) { if (!this.processingHash) {

@ -56,7 +56,7 @@ export class Web3Accounts {
} catch (e) { } catch (e) {
console.error(e) console.error(e)
} }
} }
newAccount (cb) { newAccount (cb) {

@ -59,7 +59,7 @@ export class Blocks {
nonce: bigIntToHex(tx.nonce), nonce: bigIntToHex(tx.nonce),
transactionIndex: this.TX_INDEX, transactionIndex: this.TX_INDEX,
value: bigIntToHex(tx.value), value: bigIntToHex(tx.value),
to: receipt.to ? receipt.to : null to: receipt.to ? receipt.to : null
} }
} }
}) })
@ -113,7 +113,7 @@ export class Blocks {
nonce: bigIntToHex(tx.nonce), nonce: bigIntToHex(tx.nonce),
transactionIndex: this.TX_INDEX, transactionIndex: this.TX_INDEX,
value: bigIntToHex(tx.value), value: bigIntToHex(tx.value),
to: receipt.to ? receipt.to : null to: receipt.to ? receipt.to : null
} }
} }
}) })

@ -1,5 +1,5 @@
import { toHex, toNumber, toBigInt } from 'web3-utils' import { toHex, toNumber, toBigInt } from 'web3-utils'
import { toChecksumAddress, Address, bigIntToHex, bytesToHex} from '@ethereumjs/util' import { toChecksumAddress, Address, bigIntToHex, bytesToHex } from '@ethereumjs/util'
import { processTx } from './txProcess' import { processTx } from './txProcess'
import { execution } from '@remix-project/remix-lib' import { execution } from '@remix-project/remix-lib'
import { ethers } from 'ethers' import { ethers } from 'ethers'
@ -59,7 +59,7 @@ export class Transactions {
this.txRunnerInstance = new TxRunner(this.txRunnerVMInstance, {}) this.txRunnerInstance = new TxRunner(this.txRunnerVMInstance, {})
this.txRunnerInstance.vmaccounts = accounts this.txRunnerInstance.vmaccounts = accounts
} }
methods () { methods () {
return { return {
eth_sendTransaction: this.eth_sendTransaction.bind(this), eth_sendTransaction: this.eth_sendTransaction.bind(this),
@ -163,7 +163,7 @@ export class Transactions {
this.txRunnerInstance.internalRunner.standaloneTx = false this.txRunnerInstance.internalRunner.standaloneTx = false
this.vmContext.web3().recordVMSteps(true) this.vmContext.web3().recordVMSteps(true)
if (error) return cb(error) if (error) return cb(error)
const result: any = value.result const result: any = value.result
if ((result as any).receipt?.status === '0x0' || (result as any).receipt?.status === 0) { if ((result as any).receipt?.status === '0x0' || (result as any).receipt?.status === 0) {
try { try {
const msg = `${bytesToHex(result.execResult.returnValue) || '0x00'}` const msg = `${bytesToHex(result.execResult.returnValue) || '0x00'}`

@ -26,7 +26,7 @@ export interface JSONRPCResponsePayload {
jsonrpc: string; jsonrpc: string;
} }
export type JSONRPCResponseCallback = (err: Error, result?: JSONRPCResponsePayload) => void export type JSONRPCResponseCallback = (err: Error, result?: JSONRPCResponsePayload) => void
export type State = Record<string, string> export type State = Record<string, string>
@ -83,7 +83,7 @@ export class Provider {
} }
} }
_send(payload: JSONRPCRequestPayload, callback: (err: Error, result?: JSONRPCResponsePayload) => void) { _send(payload: JSONRPCRequestPayload, callback: (err: Error, result?: JSONRPCResponsePayload) => void) {
// log.info('payload method is ', payload.method) // commented because, this floods the IDE console // log.info('payload method is ', payload.method) // commented because, this floods the IDE console
if (!this.initialized) { if (!this.initialized) {
this.pendingRequests.push({ payload, callback }) this.pendingRequests.push({ payload, callback })
@ -109,13 +109,13 @@ export class Provider {
callback(new Error('unknown method ' + payload.method)) callback(new Error('unknown method ' + payload.method))
} }
sendAsync (payload: JSONRPCRequestPayload, callback: (err: Error, result?: JSONRPCResponsePayload) => void) { sendAsync (payload: JSONRPCRequestPayload, callback: (err: Error, result?: JSONRPCResponsePayload) => void) {
return new Promise((resolve,reject)=>{ return new Promise((resolve,reject)=>{
const cb = (err, result) => { const cb = (err, result) => {
if(typeof callback==='function'){ if (typeof callback==='function'){
callback(err,result) callback(err,result)
} }
if(err){ if (err){
return reject(err) return reject(err)
} }
return resolve(result) return resolve(result)
@ -146,7 +146,7 @@ export class Provider {
} }
export function extend (web3) { export function extend (web3) {
if(!web3.remix){ if (!web3.remix){
web3.registerPlugin(new Web3TestPlugin()) web3.registerPlugin(new Web3TestPlugin())
} }
} }

@ -22,7 +22,7 @@ class Server {
start (host, port) { start (host, port) {
const wsApp = expressWs(app) const wsApp = expressWs(app)
app.use(cors()) app.use(cors())
app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json()) app.use(bodyParser.json())

@ -59,7 +59,7 @@ class StateManagerCommonStorageDump extends DefaultStateManager {
} }
shallowCopy(): StateManagerCommonStorageDump { shallowCopy(): StateManagerCommonStorageDump {
const copyState = new StateManagerCommonStorageDump({ const copyState = new StateManagerCommonStorageDump({
trie: this._trie.shallowCopy(false), trie: this._trie.shallowCopy(false),
}) })
copyState.keyHashes = this.keyHashes copyState.keyHashes = this.keyHashes
@ -93,7 +93,7 @@ class StateManagerCommonStorageDump extends DefaultStateManager {
}) })
} catch (e) { } catch (e) {
reject(e) reject(e)
} }
}) })
} }
} }
@ -110,7 +110,7 @@ export interface CustomEthersStateManagerOpts {
class CustomEthersStateManager extends StateManagerCommonStorageDump { class CustomEthersStateManager extends StateManagerCommonStorageDump {
private provider: ethers.providers.StaticJsonRpcProvider | ethers.providers.JsonRpcProvider private provider: ethers.providers.StaticJsonRpcProvider | ethers.providers.JsonRpcProvider
private blockTag: string private blockTag: string
constructor(opts: CustomEthersStateManagerOpts) { constructor(opts: CustomEthersStateManagerOpts) {
super(opts) super(opts)
if (typeof opts.provider === 'string') { if (typeof opts.provider === 'string') {
@ -188,7 +188,7 @@ class CustomEthersStateManager extends StateManagerCommonStorageDump {
async accountExists(address: Address): Promise<boolean> { async accountExists(address: Address): Promise<boolean> {
const account = await super.getAccount(address) const account = await super.getAccount(address)
if (!account.isEmpty()) return true if (!account.isEmpty()) return true
// Get merkle proof for `address` from provider // Get merkle proof for `address` from provider
const proof = await this.provider.send('eth_getProof', [address.toString(), [], this.blockTag]) const proof = await this.provider.send('eth_getProof', [address.toString(), [], this.blockTag])
@ -245,12 +245,11 @@ class CustomEthersStateManager extends StateManagerCommonStorageDump {
codeHash: hexToBytes(codeHash) codeHash: hexToBytes(codeHash)
// storageRoot: toBuffer([]), // we have to remove this in order to force the creation of the Trie in the local state. // storageRoot: toBuffer([]), // we have to remove this in order to force the creation of the Trie in the local state.
}) })
} }
return account return account
} }
} }
export type CurrentVm = { export type CurrentVm = {
vm: VM, vm: VM,
web3vm: VmProxy, web3vm: VmProxy,
@ -263,7 +262,7 @@ export class VMCommon extends Common {
/** /**
* Always return the fork set at initialization * Always return the fork set at initialization
*/ */
setHardforkBy() { setHardforkBy() {
return this._hardfork; return this._hardfork;
} }
} }
@ -281,7 +280,7 @@ export class VMContext {
txByHash: Record<string, TypedTransaction> txByHash: Record<string, TypedTransaction>
currentVm: CurrentVm currentVm: CurrentVm
web3vm: VmProxy web3vm: VmProxy
logsManager: any // LogsManager logsManager: any // LogsManager
exeResults: Record<string, TypedTransaction> exeResults: Record<string, TypedTransaction>
nodeUrl: string nodeUrl: string
blockNumber: number | 'latest' blockNumber: number | 'latest'
@ -332,7 +331,7 @@ export class VMContext {
const db = this.stateDb ? new Map(Object.entries(this.stateDb).map(([k, v]) => [k, hexToBytes(v)])) : new Map() const db = this.stateDb ? new Map(Object.entries(this.stateDb).map(([k, v]) => [k, hexToBytes(v)])) : new Map()
const mapDb = new MapDB(db) const mapDb = new MapDB(db)
const trie = await Trie.create({ useKeyHashing: true, db: mapDb, useRootPersistence: true }) const trie = await Trie.create({ useKeyHashing: true, db: mapDb, useRootPersistence: true })
stateManager = new StateManagerCommonStorageDump({ trie }) stateManager = new StateManagerCommonStorageDump({ trie })
} }
@ -357,7 +356,7 @@ export class VMContext {
const blockchain = await Blockchain.create({ common, validateBlocks: false, validateConsensus: false, genesisBlock }) const blockchain = await Blockchain.create({ common, validateBlocks: false, validateConsensus: false, genesisBlock })
const evm = await EVM.create({ common, allowUnlimitedContractSize: true, stateManager, blockchain }) const evm = await EVM.create({ common, allowUnlimitedContractSize: true, stateManager, blockchain })
const vm = await VM.create({ const vm = await VM.create({
common, common,
activatePrecompiles: true, activatePrecompiles: true,

@ -93,7 +93,7 @@ describe('blocks', () => {
it('should get block given its hash', async () => { it('should get block given its hash', async () => {
const correctBlock = await web3.eth.getBlock(0) const correctBlock = await web3.eth.getBlock(0)
const numberTransactions = await (new Promise((resolve, reject) => { const numberTransactions = await (new Promise((resolve, reject) => {
web3['_requestManager'].send({method: 'eth_getUncleCountByBlockHash', params: [correctBlock.hash]}) web3['_requestManager'].send({ method: 'eth_getUncleCountByBlockHash', params: [correctBlock.hash]})
.then(numberTransactions => resolve(numberTransactions)) .then(numberTransactions => resolve(numberTransactions))
.catch(err => reject(err)) .catch(err => reject(err))
})) }))
@ -105,7 +105,7 @@ describe('blocks', () => {
it('should get block given its number', async () => { it('should get block given its number', async () => {
const correctBlock = await web3.eth.getBlock(0) const correctBlock = await web3.eth.getBlock(0)
const numberTransactions = await (new Promise((resolve, reject) => { const numberTransactions = await (new Promise((resolve, reject) => {
web3['_requestManager'].send({method: 'eth_getUncleCountByBlockHash', params: [0]}) web3['_requestManager'].send({ method: 'eth_getUncleCountByBlockHash', params: [0]})
.then(numberTransactions => resolve(numberTransactions)) .then(numberTransactions => resolve(numberTransactions))
.catch(err => reject(err)) .catch(err => reject(err))
})) }))
@ -201,7 +201,7 @@ describe('blocks', () => {
const contract = new web3.eth.Contract(abi) const contract = new web3.eth.Contract(abi)
const accounts = await web3.eth.getAccounts() const accounts = await web3.eth.getAccounts()
const contractInstance: any = await contract.deploy({ data: code, arguments: [100] }).send({ from: accounts[0], gas: '400000' }) const contractInstance: any = await contract.deploy({ data: code, arguments: [100]}).send({ from: accounts[0], gas: '400000' })
contractInstance.currentProvider = web3.eth.currentProvider contractInstance.currentProvider = web3.eth.currentProvider
// contractInstance.givenProvider = web3.eth.currentProvider // contractInstance.givenProvider = web3.eth.currentProvider
@ -307,7 +307,7 @@ describe('blocks', () => {
const contract = new web3.eth.Contract(abi) const contract = new web3.eth.Contract(abi)
const accounts = await web3.eth.getAccounts() const accounts = await web3.eth.getAccounts()
const contractInstance: any = await contract.deploy({ data: code, arguments: [100] }).send({ from: accounts[0], gas: '400000' }) const contractInstance: any = await contract.deploy({ data: code, arguments: [100]}).send({ from: accounts[0], gas: '400000' })
contractInstance.currentProvider = web3.eth.currentProvider contractInstance.currentProvider = web3.eth.currentProvider
const value = await contractInstance.methods.get().call({ from: accounts[0] }) const value = await contractInstance.methods.get().call({ from: accounts[0] })

@ -47,7 +47,7 @@ describe('Events', () => {
toBlock: 'latest', toBlock: 'latest',
topics: ['0x342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a735', '0xdcd9c7fa0342f01013bd0bf2bec103a81936162dcebd1f0c38b1d4164c17e0fc'] topics: ['0x342827c97908e5e2f71151c08502a66d44b6f758e3ac2f1de95f02eb95f0a735', '0xdcd9c7fa0342f01013bd0bf2bec103a81936162dcebd1f0c38b1d4164c17e0fc']
}) })
// this should include the event triggered by the "set" transaction call. // this should include the event triggered by the "set" transaction call.
assert.equal(testLogs.length, 1, '1) testLogs length should be equal to 1') assert.equal(testLogs.length, 1, '1) testLogs length should be equal to 1')
assert.equal(ownerLogs.length, 1, '2) ownerLogs length should be equal to 1') assert.equal(ownerLogs.length, 1, '2) ownerLogs length should be equal to 1')
@ -80,8 +80,8 @@ pragma solidity >=0.7.0 <0.9.0;
import "hardhat/console.sol"; import "hardhat/console.sol";
contract test { contract test {
event testEvent(uint indexed value); event testEvent(uint indexed value);
function set(Owner p) public { function set(Owner p) public {
p.changeOwner(address(this)); p.changeOwner(address(this));
emit testEvent(123); emit testEvent(123);
@ -119,5 +119,5 @@ contract Owner {
function getOwner() external view returns (address) { function getOwner() external view returns (address) {
return owner; return owner;
} }
} }
*/ */

@ -13,7 +13,7 @@ describe('Misc', () => {
describe('web3_clientVersion', () => { describe('web3_clientVersion', () => {
it('should get correct remix simulator version', async () => { it('should get correct remix simulator version', async () => {
web3['_requestManager'].send({ method: 'web3_clientVersion', params: [] }) web3['_requestManager'].send({ method: 'web3_clientVersion', params: []})
.then(version => { .then(version => {
const remixVersion = require('../package.json').version const remixVersion = require('../package.json').version
assert.equal(version, 'Remix Simulator/' + remixVersion) assert.equal(version, 'Remix Simulator/' + remixVersion)
@ -24,7 +24,7 @@ describe('Misc', () => {
describe('eth_protocolVersion', () => { describe('eth_protocolVersion', () => {
it('should get protocol version', async () => { it('should get protocol version', async () => {
web3['_requestManager'].send({ method: 'eth_protocolVersion', params: [] }) web3['_requestManager'].send({ method: 'eth_protocolVersion', params: []})
.then(result => assert.equal(result, '0x3f')) .then(result => assert.equal(result, '0x3f'))
.catch(err => { throw new Error(err) }) .catch(err => { throw new Error(err) })
}) })
@ -53,7 +53,7 @@ describe('Misc', () => {
describe('web3_sha3', () => { describe('web3_sha3', () => {
it('should get result of a sha3', async () => { it('should get result of a sha3', async () => {
web3['_requestManager'].send({ method: 'web3_sha3', params: ['0x68656c6c6f20776f726c64'] }) web3['_requestManager'].send({ method: 'web3_sha3', params: ['0x68656c6c6f20776f726c64']})
.then(result => assert.equal(result, '0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad')) .then(result => assert.equal(result, '0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad'))
.catch(err => { throw new Error(err)} ) .catch(err => { throw new Error(err)} )
}) })
@ -61,7 +61,7 @@ describe('Misc', () => {
describe('eth_getCompilers', () => { describe('eth_getCompilers', () => {
it('should get list of compilers', async () => { it('should get list of compilers', async () => {
web3['_requestManager'].send({ method: 'eth_getCompilers', params: [] }) web3['_requestManager'].send({ method: 'eth_getCompilers', params: []})
.then(result => assert.equal(result, 0)) .then(result => assert.equal(result, 0))
.catch(err => { throw new Error(err) }) .catch(err => { throw new Error(err) })
}) })
@ -69,7 +69,7 @@ describe('Misc', () => {
describe('eth_compileSolidity', () => { describe('eth_compileSolidity', () => {
it('get unsupported result when requesting solidity compiler', async () => { it('get unsupported result when requesting solidity compiler', async () => {
web3['_requestManager'].send({ method: 'eth_compileSolidity', params: [] }) web3['_requestManager'].send({ method: 'eth_compileSolidity', params: []})
.then(result => assert.equal(result, 'unsupported')) .then(result => assert.equal(result, 'unsupported'))
.catch(err => { throw new Error(err) }) .catch(err => { throw new Error(err) })
}) })
@ -77,7 +77,7 @@ describe('Misc', () => {
describe('eth_compileLLL', () => { describe('eth_compileLLL', () => {
it('get unsupported result when requesting LLL compiler', async () => { it('get unsupported result when requesting LLL compiler', async () => {
web3['_requestManager'].send({ method: 'eth_compileLLL', params: [] }) web3['_requestManager'].send({ method: 'eth_compileLLL', params: []})
.then(result => assert.equal(result, 'unsupported')) .then(result => assert.equal(result, 'unsupported'))
.catch(err => { throw new Error(err) }) .catch(err => { throw new Error(err) })
}) })
@ -85,7 +85,7 @@ describe('Misc', () => {
describe('eth_compileSerpent', () => { describe('eth_compileSerpent', () => {
it('get unsupported result when requesting serpent compiler', async () => { it('get unsupported result when requesting serpent compiler', async () => {
web3['_requestManager'].send({ method: 'eth_compileSerpent', params: [] }) web3['_requestManager'].send({ method: 'eth_compileSerpent', params: []})
.then(result => assert.equal(result, 'unsupported')) .then(result => assert.equal(result, 'unsupported'))
.catch(err => { throw new Error(err)} ) .catch(err => { throw new Error(err)} )
}) })

@ -6,7 +6,7 @@ import * as assert from 'assert'
describe('Transactions', () => { describe('Transactions', () => {
before(async function () { before(async function () {
const provider = new Provider({ fork: 'shanghai'}) const provider = new Provider({ fork: 'shanghai' })
await provider.init() await provider.init()
web3.setProvider(provider as any) web3.setProvider(provider as any)
}) })

@ -20,7 +20,7 @@ export default (sources: Source, opts: CompilerInputOptions): string => {
}, },
remappings: opts.remappings || [] remappings: opts.remappings || []
} }
} }
if (opts.evmVersion) { if (opts.evmVersion) {
if (opts.evmVersion.toLowerCase() == 'default') { if (opts.evmVersion.toLowerCase() == 'default') {
opts.evmVersion = null opts.evmVersion = null

@ -82,7 +82,7 @@ export class Compiler {
*/ */
internalCompile(files: Source, missingInputs?: string[], timeStamp?: number): void { internalCompile(files: Source, missingInputs?: string[], timeStamp?: number): void {
if(timeStamp < this.state.compilationStartTime && this.state.compilerRetriggerMode == CompilerRetriggerMode.retrigger ) { if (timeStamp < this.state.compilationStartTime && this.state.compilerRetriggerMode == CompilerRetriggerMode.retrigger ) {
return return
} }
this.gatherImports(files, missingInputs, (error, input) => { this.gatherImports(files, missingInputs, (error, input) => {

@ -36,7 +36,7 @@ export default {
} }
} }
}, },
// ^ e.g: // ^ e.g:
// browser/gm.sol: Warning: Source file does not specify required compiler version! Consider adding "pragma solidity ^0.6.12 // browser/gm.sol: Warning: Source file does not specify required compiler version! Consider adding "pragma solidity ^0.6.12
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0/contracts/introspection/IERC1820Registry.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.7.4+commit.3f05b770.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0/contracts/introspection/IERC1820Registry.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.7.4+commit.3f05b770.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version

@ -161,7 +161,7 @@ export enum CompilerRetriggerMode {
} }
export interface CompilerState { export interface CompilerState {
compileJSON: ((input: SourceWithTarget, timeStamp?: number) => void) | null, compileJSON: ((input: SourceWithTarget, timeStamp?: number) => void) | null,
worker: any, worker: any,
currentVersion: string| null| undefined, currentVersion: string| null| undefined,
compilerLicense: string| null compilerLicense: string| null

@ -20,6 +20,6 @@ describe('compiler-input', () => {
expect(getValidLanguage(undefined)).toBe(null) expect(getValidLanguage(undefined)).toBe(null)
expect(getValidLanguage('')).toBe(null) expect(getValidLanguage('')).toBe(null)
expect(getValidLanguage('A')).toBe(null) expect(getValidLanguage('A')).toBe(null)
expect(getValidLanguage('Something')).toBe(null) expect(getValidLanguage('Something')).toBe(null)
}) })
}) })

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save