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. 2
      apps/circuit-compiler/src/app/services/circomPluginClient.ts
  5. 2
      apps/circuit-compiler/src/app/types/index.ts
  6. 3
      apps/debugger/.eslintrc
  7. 3
      apps/doc-gen/.eslintrc
  8. 1
      apps/doc-gen/src/app/docgen/templates.ts
  9. 2
      apps/doc-gen/src/app/docgen/utils/normalizeContractPath.ts
  10. 3
      apps/doc-viewer/.eslintrc
  11. 3
      apps/etherscan/.eslintrc
  12. 8
      apps/etherscan/src/app/EtherscanPluginClient.ts
  13. 3
      apps/learneth/.eslintrc
  14. 4
      apps/learneth/src/redux/hooks.ts
  15. 8
      apps/learneth/src/redux/models/loading.ts
  16. 40
      apps/learneth/src/redux/models/remixide.ts
  17. 26
      apps/learneth/src/redux/models/workshop.ts
  18. 6
      apps/learneth/src/redux/store.ts
  19. 8
      apps/learneth/src/remix-client.ts
  20. 3
      apps/remix-ide/src/app/editor/editor.js
  21. 7
      apps/remix-ide/src/app/files/dgitProvider.ts
  22. 3
      apps/remix-ide/src/remixAppManager.js
  23. 18
      apps/solhint/.eslintrc
  24. 3
      apps/solhint/src/app/SolhintPluginClient.ts
  25. 5
      apps/solhint/src/index.d.ts
  26. 3
      apps/solidity-compiler/.eslintrc
  27. 4
      apps/vyper/src/app/utils/types.ts
  28. 3
      apps/walletconnect/.eslintrc
  29. 16
      apps/walletconnect/src/services/WalletConnectRemixClient.ts
  30. 2
      libs/ghaction-helper/src/ethers.ts
  31. 2
      libs/ghaction-helper/src/methods.ts
  32. 5
      libs/remix-analyzer/test/analysis/staticAnalysisCommon-test.ts
  33. 3
      libs/remix-analyzer/test/analysis/staticAnalysisIntegration-test-0.5.0.ts
  34. 4
      libs/remix-analyzer/test/analysis/staticAnalysisIssues-test-0.4.24.ts
  35. 2
      libs/remix-analyzer/test/analysis/staticAnalysisIssues-test-0.5.0.ts
  36. 2
      libs/remix-astwalker/tests/resources/legacyAST.ts
  37. 1
      libs/remix-astwalker/tests/resources/newAST.ts
  38. 10
      libs/remix-core-plugin/src/lib/compiler-artefacts.ts
  39. 4
      libs/remix-core-plugin/src/lib/compiler-metadata.ts
  40. 1
      libs/remix-core-plugin/src/lib/constants/uups.ts
  41. 2
      libs/remix-core-plugin/src/lib/openzeppelin-proxy.ts
  42. 2
      libs/remix-debug/src/debugger/debugger.ts
  43. 4
      libs/remix-debug/src/init.ts
  44. 2
      libs/remix-debug/src/solidity-decoder/internalCallTree.ts
  45. 2
      libs/remix-debug/test.ts
  46. 2
      libs/remix-debug/test/codeManager.ts
  47. 8
      libs/remix-debug/test/debugger.ts
  48. 2
      libs/remix-debug/test/decoder/contracts/calldata.ts
  49. 2
      libs/remix-debug/test/decoder/contracts/intLocal.ts
  50. 2
      libs/remix-debug/test/decoder/contracts/miscLocal.ts
  51. 2
      libs/remix-debug/test/decoder/contracts/structArrayLocal.ts
  52. 3
      libs/remix-debug/test/decoder/localsTests/calldata.ts
  53. 6
      libs/remix-debug/test/decoder/stateTests/mapping.ts
  54. 4
      libs/remix-debug/test/helpers/compilerHelper.ts
  55. 27
      libs/remix-debug/test/resources/ast.ts
  56. 2
      libs/remix-debug/test/resources/testWeb3.ts
  57. 8
      libs/remix-debug/test/sourceLocationTracker.ts
  58. 2
      libs/remix-debug/test/traceManager.ts
  59. 1
      libs/remix-debug/test/vmCall.ts
  60. 6
      libs/remix-simulator/src/VmProxy.ts
  61. 2
      libs/remix-simulator/src/methods/transactions.ts
  62. 6
      libs/remix-simulator/src/provider.ts
  63. 1
      libs/remix-simulator/src/vm-context.ts
  64. 8
      libs/remix-simulator/test/blocks.ts
  65. 14
      libs/remix-simulator/test/misc.ts
  66. 2
      libs/remix-simulator/test/transactions.ts
  67. 2
      libs/remix-solidity/src/compiler/compiler.ts
  68. 2
      libs/remix-tests/src/compiler.ts
  69. 7
      libs/remix-tests/tests/testRunner.cli.spec.ts
  70. 4
      libs/remix-tests/tests/testRunner.spec.ts
  71. 7
      libs/remix-ui/editor/src/lib/remix-ui-editor.tsx
  72. 62
      libs/remix-ui/editor/src/lib/syntaxes/toml.ts
  73. 9
      libs/remix-ui/run-tab/src/lib/run-tab.tsx
  74. 13
      libs/remix-url-resolver/src/resolve.ts
  75. 8
      libs/remix-url-resolver/tests/test.ts
  76. 4
      libs/remix-ws-templates/src/script-templates/sindri/index.ts
  77. 2
      libs/remix-ws-templates/src/script-templates/sindri/run_compile.ts
  78. 2
      libs/remix-ws-templates/src/script-templates/sindri/run_prove.ts
  79. 4
      libs/remix-ws-templates/src/script-templates/sindri/utils.ts
  80. 1
      libs/remix-ws-templates/src/templates/hashchecker/scripts/groth16/groth16_zkproof.ts
  81. 2
      libs/remix-ws-templates/src/templates/semaphore/scripts/groth16/groth16_zkproof.ts
  82. 2
      libs/remix-ws-templates/src/templates/semaphore/scripts/plonk/plonk_zkproof.ts
  83. 5
      libs/remix-ws-templates/src/templates/semaphore/scripts/run_verification.ts
  84. 2
      libs/remixd/src/bin/remixd.ts
  85. 5
      libs/remixd/src/services/foundryClient.ts
  86. 5
      libs/remixd/src/services/hardhatClient.ts
  87. 1
      libs/remixd/src/services/truffleClient.ts

@ -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 = {

@ -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",
}

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

@ -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}`;

@ -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')
} }

@ -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"
}

@ -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: [
@ -448,7 +447,6 @@ deployments: {
[contractName: string]: ContractInstanceObject [contractName: string]: ContractInstanceObject
} }
} }
export type CompilerInformationObject = { export type CompilerInformationObject = {

@ -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 {
@ -50,7 +50,7 @@ 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])
@ -59,7 +59,7 @@ export class WalletConnectRemixClient extends PluginClient {
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)
@ -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 }
} }
} }

@ -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 }

@ -194,7 +194,7 @@ 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) {

@ -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')

@ -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

@ -31,9 +31,9 @@ test('staticAnalysisIssues.functionParameterPassingError', function (t) {
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;

@ -127,7 +127,7 @@ export class CompilerArtefacts extends Plugin {
_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) {
@ -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 {

@ -85,12 +85,12 @@ export class CompilerMetadata extends Plugin {
// 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'))
} }
} }

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

@ -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.

@ -97,7 +97,7 @@ 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
} }

@ -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())
} }
} }

@ -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 {

@ -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
@ -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;
} }
} }
`} ` }

@ -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)
@ -63,7 +63,6 @@ module.exports = async function (st, privateKey, contractBytecode, compilationRe
}) })
}) })
traceManager.resolveTrace(tx).then(() => { traceManager.resolveTrace(tx).then(() => {
debuggerEvent.trigger('newTraceLoaded', [traceManager.trace]) debuggerEvent.trigger('newTraceLoaded', [traceManager.trace])
}).catch((error) => { }).catch((error) => {

@ -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',
@ -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,
@ -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,14 +173,13 @@ 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;

@ -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,7 +11,7 @@ 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))
@ -23,7 +23,7 @@ tape('SourceLocationTracker', function (t) {
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)
@ -42,7 +42,7 @@ 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))
@ -54,8 +54,6 @@ tape('SourceLocationTracker', function (t) {
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 })

@ -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()
}) })

@ -4,7 +4,6 @@ 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()

@ -3,9 +3,9 @@ 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'

@ -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'

@ -112,10 +112,10 @@ export class Provider {
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())
} }
} }

@ -250,7 +250,6 @@ class CustomEthersStateManager extends StateManagerCommonStorageDump {
} }
} }
export type CurrentVm = { export type CurrentVm = {
vm: VM, vm: VM,
web3vm: VmProxy, web3vm: VmProxy,

@ -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] })

@ -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)
}) })

@ -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) => {

@ -91,7 +91,7 @@ export function compileFileOrFiles (filename: string, isDirectory: boolean, opts
const filepath: string = (isDirectory ? filename : path.dirname(filename)) const filepath: string = (isDirectory ? filename : path.dirname(filename))
const importsCallback = (url, cb) => { const importsCallback = (url, cb) => {
try { try {
if(fs.existsSync(url)) cb(null, fs.readFileSync(url, 'utf-8')) if (fs.existsSync(url)) cb(null, fs.readFileSync(url, 'utf-8'))
else { else {
const urlResolver = new RemixURLResolver() const urlResolver = new RemixURLResolver()
urlResolver.resolve(url).then((result) => cb(null, result.content)).catch((error) => cb(error.message)) urlResolver.resolve(url).then((result) => cb(null, result.content)).catch((error) => cb(error.message))

@ -9,10 +9,10 @@ describe('testRunner: remix-tests CLI', function(){
const executablePath = resolve(__dirname + '/../../../dist/libs/remix-tests/bin/remix-tests') const executablePath = resolve(__dirname + '/../../../dist/libs/remix-tests/bin/remix-tests')
const result = spawnSync('ls', { cwd: resolve(__dirname + '/../../../dist/libs/remix-tests') }) const result = spawnSync('ls', { cwd: resolve(__dirname + '/../../../dist/libs/remix-tests') })
if(result) { if (result) {
const dirContent = result.stdout.toString() const dirContent = result.stdout.toString()
// Install dependencies if 'node_modules' is not already present // Install dependencies if 'node_modules' is not already present
if(!dirContent.includes('node_modules')) { if (!dirContent.includes('node_modules')) {
execSync('yarn add @remix-project/remix-lib ../../libs/remix-lib', { cwd: resolve(__dirname + '/../../../dist/libs/remix-tests') }) execSync('yarn add @remix-project/remix-lib ../../libs/remix-lib', { cwd: resolve(__dirname + '/../../../dist/libs/remix-tests') })
execSync('yarn add @remix-project/remix-url-resolver ../../libs/remix-url-resolver', { cwd: resolve(__dirname + '/../../../dist/libs/remix-tests') }) execSync('yarn add @remix-project/remix-url-resolver ../../libs/remix-url-resolver', { cwd: resolve(__dirname + '/../../../dist/libs/remix-tests') })
execSync('yarn add @remix-project/remix-solidity ../../libs/remix-solidity', { cwd: resolve(__dirname + '/../../../dist/libs/remix-tests') }) execSync('yarn add @remix-project/remix-solidity ../../libs/remix-solidity', { cwd: resolve(__dirname + '/../../../dist/libs/remix-tests') })
@ -21,7 +21,6 @@ describe('testRunner: remix-tests CLI', function(){
} }
} }
describe('test various CLI options', function() { describe('test various CLI options', function() {
it('remix-tests version', () => { it('remix-tests version', () => {
const res = spawnSync(executablePath, ['-V']) const res = spawnSync(executablePath, ['-V'])
@ -79,8 +78,6 @@ Commands:
}) })
it('remix-tests running a test file with custom compiler version', () => { it('remix-tests running a test file with custom compiler version', () => {
const res = spawnSync(executablePath, ['--compiler', '0.7.4', resolve(__dirname + '/examples_0/assert_ok_test.sol')]) const res = spawnSync(executablePath, ['--compiler', '0.7.4', resolve(__dirname + '/examples_0/assert_ok_test.sol')])
// match initial lines // match initial lines

@ -8,8 +8,6 @@ import { deployAll } from '../src/deployer'
import { runTest, compilationInterface } from '../src/index' import { runTest, compilationInterface } from '../src/index'
import { ResultsInterface, TestCbInterface, ResultCbInterface } from '../src/index' import { ResultsInterface, TestCbInterface, ResultCbInterface } from '../src/index'
// deepEqualExcluding allows us to exclude specific keys whose values vary. // deepEqualExcluding allows us to exclude specific keys whose values vary.
// In this specific test, we'll use this helper to exclude `time` keys. // In this specific test, we'll use this helper to exclude `time` keys.
// Assertions for the existence of these will be made at the correct places. // Assertions for the existence of these will be made at the correct places.
@ -177,8 +175,6 @@ describe('testRunner', function () {
}) })
}) })
describe('assert library NOTEQUAL method tests', function () { describe('assert library NOTEQUAL method tests', function () {
const filename: string = __dirname + '/examples_0/assert_notEqual_test.sol' const filename: string = __dirname + '/examples_0/assert_notEqual_test.sol'

@ -9,6 +9,7 @@ import { solidityTokensProvider, solidityLanguageConfig } from './syntaxes/solid
import { cairoTokensProvider, cairoLanguageConfig } from './syntaxes/cairo' import { cairoTokensProvider, cairoLanguageConfig } from './syntaxes/cairo'
import { zokratesTokensProvider, zokratesLanguageConfig } from './syntaxes/zokrates' import { zokratesTokensProvider, zokratesLanguageConfig } from './syntaxes/zokrates'
import { moveTokenProvider, moveLanguageConfig } from './syntaxes/move' import { moveTokenProvider, moveLanguageConfig } from './syntaxes/move'
import { tomlLanguageConfig, tomlTokenProvider } from './syntaxes/toml'
import { monacoTypes } from '@remix-ui/editor' import { monacoTypes } from '@remix-ui/editor'
import { loadTypes } from './web-types' import { loadTypes } from './web-types'
import { retrieveNodesAtPosition } from './helpers/retrieveNodesAtPosition' import { retrieveNodesAtPosition } from './helpers/retrieveNodesAtPosition'
@ -359,6 +360,8 @@ export const EditorUI = (props: EditorUIProps) => {
monacoRef.current.editor.setModelLanguage(file.model, 'remix-move') monacoRef.current.editor.setModelLanguage(file.model, 'remix-move')
} else if (file.language === 'circom') { } else if (file.language === 'circom') {
monacoRef.current.editor.setModelLanguage(file.model, 'remix-circom') monacoRef.current.editor.setModelLanguage(file.model, 'remix-circom')
} else if (file.language === 'toml') {
monacoRef.current.editor.setModelLanguage(file.model, 'remix-toml')
} }
}, [props.currentFile, props.isDiff]) }, [props.currentFile, props.isDiff])
@ -911,6 +914,7 @@ export const EditorUI = (props: EditorUIProps) => {
monacoRef.current.languages.register({ id: 'remix-zokrates' }) monacoRef.current.languages.register({ id: 'remix-zokrates' })
monacoRef.current.languages.register({ id: 'remix-move' }) monacoRef.current.languages.register({ id: 'remix-move' })
monacoRef.current.languages.register({ id: 'remix-circom' }) monacoRef.current.languages.register({ id: 'remix-circom' })
monacoRef.current.languages.register({ id: 'remix-toml' })
// Allow JSON schema requests // Allow JSON schema requests
monacoRef.current.languages.json.jsonDefaults.setDiagnosticsOptions({ enableSchemaRequest: true }) monacoRef.current.languages.json.jsonDefaults.setDiagnosticsOptions({ enableSchemaRequest: true })
@ -931,6 +935,9 @@ export const EditorUI = (props: EditorUIProps) => {
monacoRef.current.languages.setMonarchTokensProvider('remix-circom', circomTokensProvider as any) monacoRef.current.languages.setMonarchTokensProvider('remix-circom', circomTokensProvider as any)
monacoRef.current.languages.setLanguageConfiguration('remix-circom', circomLanguageConfig(monacoRef.current) as any) monacoRef.current.languages.setLanguageConfiguration('remix-circom', circomLanguageConfig(monacoRef.current) as any)
monacoRef.current.languages.setMonarchTokensProvider('remix-toml', tomlTokenProvider as any)
monacoRef.current.languages.setLanguageConfiguration('remix-toml', tomlLanguageConfig as any)
monacoRef.current.languages.registerDefinitionProvider('remix-solidity', new RemixDefinitionProvider(props, monaco)) monacoRef.current.languages.registerDefinitionProvider('remix-solidity', new RemixDefinitionProvider(props, monaco))
monacoRef.current.languages.registerDocumentHighlightProvider('remix-solidity', new RemixHighLightProvider(props, monaco)) monacoRef.current.languages.registerDocumentHighlightProvider('remix-solidity', new RemixHighLightProvider(props, monaco))
monacoRef.current.languages.registerReferenceProvider('remix-solidity', new RemixReferenceProvider(props, monaco)) monacoRef.current.languages.registerReferenceProvider('remix-solidity', new RemixReferenceProvider(props, monaco))

@ -0,0 +1,62 @@
/* eslint-disable no-useless-escape */
export const tomlLanguageConfig = {
comments: {
lineComment: "#",
},
brackets: [
["{", "}"],
["[", "]"],
["(", ")"],
],
autoClosingPairs: [
{ open: "{", close: "}" },
{ open: "[", close: "]" },
{ open: "(", close: ")" },
{ open: '"', close: '"' },
{ open: "'", close: "'" },
],
surroundingPairs: [
{ open: "{", close: "}" },
{ open: "[", close: "]" },
{ open: "(", close: ")" },
{ open: '"', close: '"' },
{ open: "'", close: "'" },
],
}
export const tomlTokenProvider = {
defaultToken: "",
tokenPostfix: ".toml",
escapes:
/\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
tokenizer: {
root: [
[/([a-zA-Z0-9_-]+)(\s*)(=)/, ["variable.name", "operators", ""]],
[/\[[a-zA-Z0-9_.-]+\]/, "type.identifier"],
[/\s*((#).*)$/, "comment"],
[/\d*\.\d+([eE][\-+]?\d+)?/, "number.float"],
[/0[xX][0-9a-fA-F]+/, "number.hex"],
[/\d+/, "number"],
[/"([^"\\]|\\.)*$/, "string.invalid"],
[/'([^'\\]|\\.)*$/, "string.invalid"],
[/"/, "string", "@string_double"],
[/'/, "string", "@string_single"],
],
string_double: [
[/[^\\"]+/, "string"],
[/@escapes/, "string.escape"],
[/\\./, "string.escape.invalid"],
[/"/, "string", "@pop"],
],
string_single: [
[/[^\\']+/, "string"],
[/@escapes/, "string.escape"],
[/\\./, "string.escape.invalid"],
[/'/, "string", "@pop"],
],
},
}

@ -326,7 +326,14 @@ export function RunTabUI(props: RunTabProps) {
getFuncABIInputs={getFuncABIValues} getFuncABIInputs={getFuncABIValues}
exEnvironment={runTab.selectExEnv} exEnvironment={runTab.selectExEnv}
editInstance={(instance) => { editInstance={(instance) => {
plugin.call('dapp-draft', 'edit', { address: instance.address, abi: instance.contractData.abi, name: instance.name, network: runTab.networkName }) plugin.call('dapp-draft', 'edit', {
address: instance.address,
abi: instance.contractData.abi,
name: instance.name,
network: runTab.networkName,
devdoc: instance.contractData.object.devdoc,
methodIdentifiers: instance.contractData.object.evm.methodIdentifiers,
})
}} }}
/> />
</div> </div>

@ -64,7 +64,7 @@ export class RemixURLResolver {
// eslint-disable-next-line no-useless-catch // eslint-disable-next-line no-useless-catch
try { try {
const req = `https://raw.githubusercontent.com/${root}/${reference}/${filePath}` const req = `https://raw.githubusercontent.com/${root}/${reference}/${filePath}`
const response: AxiosResponse = await axios.get(req, { transformResponse: [] }) const response: AxiosResponse = await axios.get(req, { transformResponse: []})
return { content: response.data, cleanUrl: root + '/' + filePath } return { content: response.data, cleanUrl: root + '/' + filePath }
} catch (e) { } catch (e) {
throw e throw e
@ -79,7 +79,7 @@ export class RemixURLResolver {
async handleHttp(url: string, cleanUrl: string): Promise<HandlerResponse> { async handleHttp(url: string, cleanUrl: string): Promise<HandlerResponse> {
// eslint-disable-next-line no-useless-catch // eslint-disable-next-line no-useless-catch
try { try {
const response: AxiosResponse = await axios.get(url, { transformResponse: [] }) const response: AxiosResponse = await axios.get(url, { transformResponse: []})
return { content: response.data, cleanUrl } return { content: response.data, cleanUrl }
} catch (e) { } catch (e) {
throw e throw e
@ -94,7 +94,7 @@ export class RemixURLResolver {
async handleHttps(url: string, cleanUrl: string): Promise<HandlerResponse> { async handleHttps(url: string, cleanUrl: string): Promise<HandlerResponse> {
// eslint-disable-next-line no-useless-catch // eslint-disable-next-line no-useless-catch
try { try {
const response: AxiosResponse = await axios.get(url, { transformResponse: [] }) const response: AxiosResponse = await axios.get(url, { transformResponse: []})
return { content: response.data, cleanUrl } return { content: response.data, cleanUrl }
} catch (e) { } catch (e) {
throw e throw e
@ -106,7 +106,7 @@ export class RemixURLResolver {
try { try {
const bzz = new Bzz({ url: this.protocol + '//swarm-gateways.net' }) const bzz = new Bzz({ url: this.protocol + '//swarm-gateways.net' })
const url = bzz.getDownloadURL(cleanUrl, { mode: 'raw' }) const url = bzz.getDownloadURL(cleanUrl, { mode: 'raw' })
const response: AxiosResponse = await axios.get(url, { transformResponse: [] }) const response: AxiosResponse = await axios.get(url, { transformResponse: []})
return { content: response.data, cleanUrl } return { content: response.data, cleanUrl }
} catch (e) { } catch (e) {
throw e throw e
@ -125,7 +125,7 @@ export class RemixURLResolver {
const req = 'https://jqgt.remixproject.org/' + url const req = 'https://jqgt.remixproject.org/' + url
// If you don't find greeter.sol on ipfs gateway use local // If you don't find greeter.sol on ipfs gateway use local
// const req = 'http://localhost:8080/' + url // const req = 'http://localhost:8080/' + url
const response: AxiosResponse = await axios.get(req, { transformResponse: [] }) const response: AxiosResponse = await axios.get(req, { transformResponse: []})
return { content: response.data, cleanUrl: url.replace('ipfs/', '') } return { content: response.data, cleanUrl: url.replace('ipfs/', '') }
} catch (e) { } catch (e) {
throw e throw e
@ -190,7 +190,7 @@ export class RemixURLResolver {
for (let i = 0; i < npm_urls.length; i++) { for (let i = 0; i < npm_urls.length; i++) {
try { try {
const req = npm_urls[i] + url const req = npm_urls[i] + url
const response: AxiosResponse = await axios.get(req, { transformResponse: [] }) const response: AxiosResponse = await axios.get(req, { transformResponse: []})
content = response.data content = response.data
break break
} catch (e) { } catch (e) {
@ -202,7 +202,6 @@ export class RemixURLResolver {
return { content, cleanUrl: url } return { content, cleanUrl: url }
} }
getHandlers (): Handler[] { getHandlers (): Handler[] {
return [ return [
{ {

@ -109,7 +109,7 @@ describe('testRunner', () => {
it('should return contract content of given github path', () => { it('should return contract content of given github path', () => {
const expt: object = { const expt: object = {
cleanUrl: 'ethereum/remix-project/libs/remix-url-resolver/tests/example_1/greeter.sol', cleanUrl: 'ethereum/remix-project/libs/remix-url-resolver/tests/example_1/greeter.sol',
content: fs.readFileSync(__dirname + '/example_1/greeter.sol', { encoding: 'utf8'}), content: fs.readFileSync(__dirname + '/example_1/greeter.sol', { encoding: 'utf8' }),
type: 'github' type: 'github'
} }
assert.deepEqual(results, expt) assert.deepEqual(results, expt)
@ -139,7 +139,7 @@ describe('testRunner', () => {
it('should return contract content of given github path', () => { it('should return contract content of given github path', () => {
const expt: object = { const expt: object = {
cleanUrl: 'ethereum/remix-project/libs/remix-url-resolver/tests/example_1/greeter.sol', cleanUrl: 'ethereum/remix-project/libs/remix-url-resolver/tests/example_1/greeter.sol',
content: fs.readFileSync(__dirname + '/example_1/greeter.sol', { encoding: 'utf8'}) + '\n', content: fs.readFileSync(__dirname + '/example_1/greeter.sol', { encoding: 'utf8' }) + '\n',
type: 'github' type: 'github'
} }
assert.deepEqual(results, expt) assert.deepEqual(results, expt)
@ -169,7 +169,7 @@ describe('testRunner', () => {
it('should return contract content of given github path', () => { it('should return contract content of given github path', () => {
const expt: object = { const expt: object = {
cleanUrl: 'ethereum/remix-project/libs/remix-url-resolver/tests/example_1/greeter.sol', cleanUrl: 'ethereum/remix-project/libs/remix-url-resolver/tests/example_1/greeter.sol',
content: fs.readFileSync(__dirname + '/example_1/greeter.sol', { encoding: 'utf8'}), content: fs.readFileSync(__dirname + '/example_1/greeter.sol', { encoding: 'utf8' }),
type: 'github' type: 'github'
} }
assert.deepEqual(results, expt) assert.deepEqual(results, expt)
@ -257,7 +257,7 @@ describe('testRunner', () => {
assert.equal(Object.keys(results).length, 3) assert.equal(Object.keys(results).length, 3)
}) })
it('should return contract content from IPFS url', () => { it('should return contract content from IPFS url', () => {
const content = fs.readFileSync(__dirname + '/example_1/greeter.sol', { encoding: 'utf8'}) const content = fs.readFileSync(__dirname + '/example_1/greeter.sol', { encoding: 'utf8' })
const expt: object = { const expt: object = {
content: content, content: content,
cleanUrl: 'QmcuCKyokk9Z6f65ADAADNiS2R2xCjfRkv7mYBSWDwtA7M', cleanUrl: 'QmcuCKyokk9Z6f65ADAADNiS2R2xCjfRkv7mYBSWDwtA7M',

@ -71,12 +71,12 @@ export const sindriScripts = async (plugin: any) => {
if (a.isTemplateEntrypoint !== b.isTemplateEntrypoint) return +b.isTemplateEntrypoint - +a.isTemplateEntrypoint if (a.isTemplateEntrypoint !== b.isTemplateEntrypoint) return +b.isTemplateEntrypoint - +a.isTemplateEntrypoint
return a.path.localeCompare(b.path) return a.path.localeCompare(b.path)
}) })
.map(({path}) => path)[0] || './circuit.circom' .map(({ path }) => path)[0] || './circuit.circom'
sindriManifest.circuitPath = circomCircuitPath sindriManifest.circuitPath = circomCircuitPath
} }
// Derive the circuit name from the workspace name. // Derive the circuit name from the workspace name.
const {name: workspaceName} = await plugin.call('filePanel', 'getCurrentWorkspace') const { name: workspaceName } = await plugin.call('filePanel', 'getCurrentWorkspace')
sindriManifest.name = sindriManifest.name =
workspaceName workspaceName
.replace(/\s*-+\s*\d*$/, '') .replace(/\s*-+\s*\d*$/, '')

@ -1,4 +1,4 @@
import {compile} from './utils' import { compile } from './utils'
const main = async () => { const main = async () => {
const circuit = await compile() const circuit = await compile()

@ -1,4 +1,4 @@
import {prove} from './utils' import { prove } from './utils'
// You must modify the input signals to include the data you're trying to generate a proof for. // You must modify the input signals to include the data you're trying to generate a proof for.
const signals: {[name: string]: number | string} = {} const signals: {[name: string]: number | string} = {}

@ -1,5 +1,5 @@
import sindriClient from 'sindri' import sindriClient from 'sindri'
import type {CircuitInfoResponse, ProofInfoResponse} from 'sindri' import type { CircuitInfoResponse, ProofInfoResponse } from 'sindri'
sindriClient.logLevel = 'info' sindriClient.logLevel = 'info'
@ -9,7 +9,7 @@ const authorize = async () => {
if (!apiKey) { if (!apiKey) {
throw new Error('Missing API key.') throw new Error('Missing API key.')
} }
sindriClient.authorize({apiKey}) sindriClient.authorize({ apiKey })
} catch { } catch {
const message = 'No Sindri API key found. Please click the gear in the lower left corner to open the settings page, and add your API key under "Sindri Credentials".' const message = 'No Sindri API key found. Please click the gear in the lower left corner to open the settings page, and add your API key under "Sindri Credentials".'
await remix.call('notification', 'toast', message) await remix.call('notification', 'toast', message)

@ -51,7 +51,6 @@ const logger = {
console.log('check') console.log('check')
await snarkjs.wtns.check(r1cs, wtns, logger); await snarkjs.wtns.check(r1cs, wtns, logger);
console.log('prove') console.log('prove')
const { proof, publicSignals } = await snarkjs.groth16.prove(zkey_final, wtns); const { proof, publicSignals } = await snarkjs.groth16.prove(zkey_final, wtns);

@ -50,7 +50,7 @@ function hash(message: any): bigint {
for (let k = 0; k < 2; k++) { for (let k = 0; k < 2; k++) {
const identityTrapdoor = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32))) const identityTrapdoor = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32)))
const identityNullifier = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32))) const identityNullifier = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32)))
secrets.push({identityTrapdoor, identityNullifier}) secrets.push({ identityTrapdoor, identityNullifier })
const secret = poseidon([identityNullifier, identityTrapdoor]) const secret = poseidon([identityNullifier, identityTrapdoor])
const identityCommitment = poseidon([secret]) const identityCommitment = poseidon([secret])

@ -50,7 +50,7 @@ function hash(message: any): bigint {
for (let k = 0; k < 2; k++) { for (let k = 0; k < 2; k++) {
const identityTrapdoor = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32))) const identityTrapdoor = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32)))
const identityNullifier = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32))) const identityNullifier = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32)))
secrets.push({identityTrapdoor, identityNullifier}) secrets.push({ identityTrapdoor, identityNullifier })
const secret = poseidon([identityNullifier, identityTrapdoor]) const secret = poseidon([identityNullifier, identityTrapdoor])
const identityCommitment = poseidon([secret]) const identityCommitment = poseidon([secret])

@ -47,7 +47,7 @@ function hash(message: any): bigint {
for (let k = 0; k < 2; k++) { for (let k = 0; k < 2; k++) {
const identityTrapdoor = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32))) const identityTrapdoor = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32)))
const identityNullifier = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32))) const identityNullifier = BigInt(ethers.utils.hexlify(ethers.utils.randomBytes(32)))
secrets.push({identityTrapdoor, identityNullifier}) secrets.push({ identityTrapdoor, identityNullifier })
const secret = poseidon([identityNullifier, identityTrapdoor]) const secret = poseidon([identityNullifier, identityTrapdoor])
const identityCommitment = poseidon([secret]) const identityCommitment = poseidon([secret])
@ -86,7 +86,6 @@ function hash(message: any): bigint {
console.log('check') console.log('check')
await snarkjs.wtns.check(r1cs, wtns, logger); await snarkjs.wtns.check(r1cs, wtns, logger);
console.log('prove') console.log('prove')
const { proof, publicSignals } = await snarkjs.groth16.prove(zkey_final, wtns); const { proof, publicSignals } = await snarkjs.groth16.prove(zkey_final, wtns);
@ -94,8 +93,6 @@ function hash(message: any): bigint {
console.log('zk proof validity', verified); console.log('zk proof validity', verified);
proof1.root.toString() === publicSignals[0] ? console.log('merkle proof valid') : console.log('merkle proof invalid') proof1.root.toString() === publicSignals[0] ? console.log('merkle proof valid') : console.log('merkle proof invalid')
} catch (e) { } catch (e) {
console.error(e.message) console.error(e.message)
} }

@ -77,7 +77,7 @@ function errorHandler (error: any, service: string) {
const options = program.opts(); const options = program.opts();
await warnLatestVersion() await warnLatestVersion()
if(options.install && !options.readOnly) { if (options.install && !options.readOnly) {
if (options.install.toLowerCase() === 'slither') require('./../scripts/installSlither') if (options.install.toLowerCase() === 'slither') require('./../scripts/installSlither')
process.exit(0) process.exit(0)
} }

@ -52,7 +52,7 @@ export class FoundryClient extends PluginClient {
listenOnFoundryFolder() { listenOnFoundryFolder() {
console.log('Foundry out folder doesn\'t exist... waiting for the compilation.') console.log('Foundry out folder doesn\'t exist... waiting for the compilation.')
try { try {
if(this.watcher) this.watcher.close() if (this.watcher) this.watcher.close()
this.watcher = chokidar.watch(this.currentSharedFolder, { depth: 1, ignorePermissionErrors: true, ignoreInitial: true }) this.watcher = chokidar.watch(this.currentSharedFolder, { depth: 1, ignorePermissionErrors: true, ignoreInitial: true })
// watch for new folders // watch for new folders
this.watcher.on('addDir', () => { this.watcher.on('addDir', () => {
@ -142,7 +142,7 @@ export class FoundryClient extends PluginClient {
listenOnFoundryCompilation() { listenOnFoundryCompilation() {
try { try {
if(this.watcher) this.watcher.close() if (this.watcher) this.watcher.close()
this.watcher = chokidar.watch(this.cachePath, { depth: 0, ignorePermissionErrors: true, ignoreInitial: true }) this.watcher = chokidar.watch(this.cachePath, { depth: 0, ignorePermissionErrors: true, ignoreInitial: true })
this.watcher.on('change', async () => await this.triggerProcessArtifact()) this.watcher.on('change', async () => await this.triggerProcessArtifact())
this.watcher.on('add', async () => await this.triggerProcessArtifact()) this.watcher.on('add', async () => await this.triggerProcessArtifact())
@ -193,7 +193,6 @@ export class FoundryClient extends PluginClient {
console.log('\x1b[32m%s\x1b[0m', 'sources input not found, please update Foundry to the latest version.') console.log('\x1b[32m%s\x1b[0m', 'sources input not found, please update Foundry to the latest version.')
} }
compilationResultPart.compilationTarget = contentJSON.ast.absolutePath compilationResultPart.compilationTarget = contentJSON.ast.absolutePath
// extract data // extract data
if (!compilationResultPart.output['sources'][contentJSON.ast.absolutePath]) compilationResultPart.output['sources'][contentJSON.ast.absolutePath] = {} if (!compilationResultPart.output['sources'][contentJSON.ast.absolutePath]) compilationResultPart.output['sources'][contentJSON.ast.absolutePath] = {}

@ -143,13 +143,12 @@ export class HardhatClient extends PluginClient {
} }
}, 1000) }, 1000)
} }
listenOnHardHatFolder() { listenOnHardHatFolder() {
console.log('Hardhat artifacts folder doesn\'t exist... waiting for the compilation.') console.log('Hardhat artifacts folder doesn\'t exist... waiting for the compilation.')
try { try {
if(this.watcher) this.watcher.close() if (this.watcher) this.watcher.close()
this.watcher = chokidar.watch(this.currentSharedFolder, { depth: 2, ignorePermissionErrors: true, ignoreInitial: true }) this.watcher = chokidar.watch(this.currentSharedFolder, { depth: 2, ignorePermissionErrors: true, ignoreInitial: true })
// watch for new folders // watch for new folders
this.watcher.on('addDir', () => { this.watcher.on('addDir', () => {
@ -171,7 +170,7 @@ export class HardhatClient extends PluginClient {
listenOnHardhatCompilation() { listenOnHardhatCompilation() {
try { try {
console.log('listening on Hardhat compilation...') console.log('listening on Hardhat compilation...')
if(this.watcher) this.watcher.close() if (this.watcher) this.watcher.close()
this.watcher = chokidar.watch(this.buildPath, { depth: 1, ignorePermissionErrors: true, ignoreInitial: true }) this.watcher = chokidar.watch(this.buildPath, { depth: 1, ignorePermissionErrors: true, ignoreInitial: true })
this.watcher.on('change', async () => await this.triggerProcessArtifact()) this.watcher.on('change', async () => await this.triggerProcessArtifact())
this.watcher.on('add', async () => await this.triggerProcessArtifact()) this.watcher.on('add', async () => await this.triggerProcessArtifact())

@ -100,7 +100,6 @@ export class TruffleClient extends PluginClient {
return true return true
} }
private async processArtifact() { private async processArtifact() {
if (!this.checkPath()) return if (!this.checkPath()) return
const folderFiles = await fs.readdir(this.buildPath) const folderFiles = await fs.readdir(this.buildPath)

Loading…
Cancel
Save