do less set interval

pull/3481/head
yann300 2 years ago
parent 9ab886902a
commit dde5be5433
  1. 18
      apps/remix-ide/src/app/providers/injected-provider.tsx
  2. 46
      apps/remix-ide/src/blockchain/blockchain.js
  3. 1
      apps/remix-ide/src/blockchain/execution-context.js
  4. 2
      apps/remix-ide/src/blockchain/providers/injected.js
  5. 2
      apps/remix-ide/src/blockchain/providers/node.js
  6. 45
      apps/remix-ide/src/blockchain/providers/vm.js
  7. 13
      libs/remix-core-plugin/src/lib/compiler-fetch-and-compile.ts
  8. 1
      libs/remix-ui/run-tab/src/lib/actions/deploy.ts
  9. 29
      libs/remix-ui/run-tab/src/lib/actions/events.ts
  10. 8
      libs/remix-ui/run-tab/src/lib/actions/index.ts
  11. 2
      libs/remix-ui/run-tab/src/lib/types/blockchain.d.ts
  12. 2
      libs/remix-ui/run-tab/src/lib/types/injected.d.ts
  13. 2
      libs/remix-ui/run-tab/src/lib/types/node.d.ts
  14. 2
      libs/remix-ui/run-tab/src/lib/types/vm.d.ts

@ -10,6 +10,8 @@ const noInjectedProviderMsg = 'No injected provider found. Make sure your provid
export class InjectedProvider extends Plugin implements IProvider {
provider: any
options: { [id: string] : any } = {}
listenerAccountsChanged: (accounts: Array<string>) => void
listenerChainChanged: (chainId: number) => void
constructor (profile) {
super(profile)
@ -18,6 +20,22 @@ export class InjectedProvider extends Plugin implements IProvider {
}
}
onActivation(): void {
this.listenerAccountsChanged = (accounts: Array<string>) => {
this.emit('accountsChanged', accounts)
}
this.listenerChainChanged = (chainId: number) => {
this.emit('chainChanged', chainId)
}
(window as any).ethereum.on('accountsChanged', this.listenerAccountsChanged);
(window as any).ethereum.on('chainChanged', this.listenerChainChanged);
}
onDeactivation(): void {
(window as any).ethereum.removeListener('accountsChanged', this.listenerAccountsChanged)
(window as any).ethereum.removeListener('chainChanged', this.listenerChainChanged)
}
askPermission (throwIfNoInjectedProvider) {
if ((typeof (window as any).ethereum) !== "undefined" && (typeof (window as any).ethereum.request) === "function") {
(window as any).ethereum.request({ method: "eth_requestAccounts" })

@ -23,7 +23,7 @@ const profile = {
name: 'blockchain',
displayName: 'Blockchain',
description: 'Blockchain - Logic',
methods: ['getCode', 'getTransactionReceipt', 'addProvider', 'removeProvider', 'getCurrentFork', 'web3VM'],
methods: ['getCode', 'getTransactionReceipt', 'addProvider', 'removeProvider', 'getCurrentFork', 'web3VM', 'getProvider'],
version: packageJson.version
}
@ -48,33 +48,50 @@ export class Blockchain extends Plugin {
}, _ => this.executionContext.web3(), _ => this.executionContext.currentblockGasLimit())
this.txRunner = new TxRunner(web3Runner, { runAsync: true })
this.executionContext.event.register('contextChanged', this.resetEnvironment.bind(this))
this.networkcallid = 0
this.networkStatus = { name: ' - ', id: ' - ' }
this.setupEvents()
this.setupProviders()
}
_triggerEvent (name, args) {
this.event.trigger(name, args)
this.emit(name, ...args)
}
onActivation () {
this.on('injected', 'chainChanged', () => {
this.detectNetwork((error, network) => {
this.networkStatus = { network, error }
this._triggerEvent('networkStatus', [this.networkStatus])
})
})
}
onDeactivation () {
this.off('injected', 'chainChanged')
}
setupEvents () {
this.executionContext.event.register('contextChanged', (context, silent) => {
this.event.trigger('contextChanged', [context, silent])
this.executionContext.event.register('contextChanged', async (context) => {
await this.resetEnvironment()
this._triggerEvent('contextChanged', [context])
})
this.executionContext.event.register('addProvider', (network) => {
this.event.trigger('addProvider', [network])
this._triggerEvent('addProvider', [network])
})
this.executionContext.event.register('removeProvider', (name) => {
this.event.trigger('removeProvider', [name])
this._triggerEvent('removeProvider', [name])
})
setInterval(() => {
this.detectNetwork((error, network) => {
this.networkStatus = { network, error }
this.event.trigger('networkStatus', [this.networkStatus])
this._triggerEvent('networkStatus', [this.networkStatus])
})
}, 1000)
}, 30000)
}
getCurrentNetworkStatus () {
@ -480,12 +497,11 @@ export class Blockchain extends Plugin {
// NOTE: the config is only needed because exectuionContext.init does
// if config.get('settings/always-use-vm'), we can simplify this later
resetAndInit (config, transactionContextAPI) {
async resetAndInit (config, transactionContextAPI) {
this.transactionContextAPI = transactionContextAPI
this.executionContext.init(config)
this.executionContext.stopListenOnLastBlock()
this.executionContext.listenOnLastBlock()
this.resetEnvironment()
}
addProvider (provider) {
@ -504,8 +520,8 @@ export class Blockchain extends Plugin {
})
}
resetEnvironment () {
this.getCurrentProvider().resetEnvironment()
async resetEnvironment () {
await this.getCurrentProvider().resetEnvironment()
// TODO: most params here can be refactored away in txRunner
const web3Runner = new TxRunnerWeb3({
config: this.config,
@ -674,7 +690,7 @@ export class Blockchain extends Plugin {
if (!tx.timestamp) tx.timestamp = Date.now()
const timestamp = tx.timestamp
this.event.trigger('initiatingTransaction', [timestamp, tx, payLoad])
this._triggerEvent('initiatingTransaction', [timestamp, tx, payLoad])
try {
this.txRunner.rawRun(tx, confirmationCb, continueCb, promptCb,
async (error, result) => {
@ -698,7 +714,7 @@ export class Blockchain extends Plugin {
}
const eventName = (tx.useCall ? 'callExecuted' : 'transactionExecuted')
this.event.trigger(eventName, [error, tx.from, tx.to, tx.data, tx.useCall, result, timestamp, payLoad])
this._triggerEvent(eventName, [error, tx.from, tx.to, tx.data, tx.useCall, result, timestamp, payLoad])
return resolve({ result, tx })
}
)

@ -37,6 +37,7 @@ export class ExecutionContext {
if (config.get('settings/always-use-vm')) {
this.executionContext = 'vm-merge'
}
this.event.trigger('contextChanged', [this.executionContext])
}
getProvider () {

@ -16,7 +16,7 @@ class InjectedProvider {
})
}
resetEnvironment () {
async resetEnvironment () {
/* Do nothing. */
}

@ -24,7 +24,7 @@ class NodeProvider {
})
}
resetEnvironment () {
async resetEnvironment () {
/* Do nothing. */
}

@ -18,7 +18,7 @@ class VMProvider {
})
}
resetEnvironment () {
async resetEnvironment () {
if (this.worker) this.worker.terminate()
this.accounts = {}
this.worker = new Worker(new URL('./worker-vm', import.meta.url))
@ -26,28 +26,33 @@ class VMProvider {
let incr = 0
const stamps = {}
this.worker.addEventListener('message', (msg) => {
if (msg.data.cmd === 'sendAsyncResult' && stamps[msg.data.stamp]) {
stamps[msg.data.stamp](msg.data.error, msg.data.result)
} else if (msg.data.cmd === 'initiateResult') {
if (!msg.data.error) {
this.provider = {
sendAsync: (query, callback) => {
const stamp = Date.now() + incr
incr++
stamps[stamp] = callback
this.worker.postMessage({ cmd: 'sendAsync', query, stamp })
return new Promise((resolve, reject) => {
this.worker.addEventListener('message', (msg) => {
if (msg.data.cmd === 'sendAsyncResult' && stamps[msg.data.stamp]) {
stamps[msg.data.stamp](msg.data.error, msg.data.result)
} else if (msg.data.cmd === 'initiateResult') {
if (!msg.data.error) {
this.provider = {
sendAsync: (query, callback) => {
const stamp = Date.now() + incr
incr++
stamps[stamp] = callback
this.worker.postMessage({ cmd: 'sendAsync', query, stamp })
}
}
this.web3 = new Web3(this.provider)
extend(this.web3)
this.accounts = {}
this.executionContext.setWeb3(this.executionContext.getProvider(), this.web3)
resolve({})
} else {
reject(new Error(msg.data.error))
}
this.web3 = new Web3(this.provider)
extend(this.web3)
this.accounts = {}
this.executionContext.setWeb3(this.executionContext.getProvider(), this.web3)
}
}
})
this.worker.postMessage({ cmd: 'init', fork: this.executionContext.getCurrentFork(), nodeUrl: provider?.options['nodeUrl'], blockNumber: provider?.options['blockNumber']})
})
this.worker.postMessage({ cmd: 'init', fork: this.executionContext.getCurrentFork(), nodeUrl: provider?.options['nodeUrl'], blockNumber: provider?.options['blockNumber']})
})
}
// TODO: is still here because of the plugin API

@ -134,7 +134,18 @@ export class FetchAndCompile extends Plugin {
if (!data) {
setTimeout(_ => this.emit('notFound', contractAddress), 0)
this.unresolvedAddresses.push(contractAddress)
return localCompilation()
const compilation = await localCompilation()
if (compilation) {
let found = false
compilation.visitContracts((contract) => {
found = util.compareByteCode(codeAtAddress, '0x' + contract.object.evm.deployedBytecode.object)
return found
})
if (found) {
await this.call('compilerArtefacts', 'addResolvedContract', contractAddress, compilation)
return compilation
}
}
}
const { settings, compilationTargets } = data

@ -322,6 +322,7 @@ export const updateInstanceBalance = (plugin: RunTab) => {
if (plugin.REACT_API?.instances?.instanceList?.length) {
for (const instance of plugin.REACT_API.instances.instanceList) {
plugin.blockchain.getBalanceInEther(instance.address, (err, balInEth) => {
console.log('balance of ',instance.address, balInEth)
if (!err) instance.balance = balInEth
})
}

@ -1,13 +1,15 @@
import { envChangeNotification } from "@remix-ui/helper"
import { RunTab } from "../types/run-tab"
import { setExecutionContext, setFinalContext, updateAccountBalances } from "./account"
import { setExecutionContext, setFinalContext, updateAccountBalances, fillAccountsList } from "./account"
import { addExternalProvider, addInstance, addNewProxyDeployment, removeExternalProvider, setNetworkNameFromProvider } from "./actions"
import { addDeployOption, clearAllInstances, clearRecorderCount, fetchContractListSuccess, resetProxyDeployments, resetUdapp, setCurrentContract, setCurrentFile, setLoadType, setRecorderCount, setRemixDActivated, setSendValue } from "./payload"
import { addDeployOption, clearAllInstances, clearRecorderCount, fetchContractListSuccess, resetProxyDeployments, resetUdapp, setCurrentContract, setCurrentFile, setLoadType, setRecorderCount, setRemixDActivated, setSendValue, fetchAccountsListSuccess } from "./payload"
import { updateInstanceBalance } from './deploy'
import { CompilerAbstract } from '@remix-project/remix-solidity'
import BN from 'bn.js'
import Web3 from 'web3'
import { Plugin } from "@remixproject/engine"
import { getNetworkProxyAddresses } from "./deploy"
import { shortenAddress } from "@remix-ui/helper"
const _paq = window._paq = window._paq || []
@ -22,7 +24,7 @@ export const setupEvents = (plugin: RunTab, dispatch: React.Dispatch<any>) => {
updateAccountBalances(plugin, dispatch)
})
plugin.blockchain.event.register('contextChanged', (context, silent) => {
plugin.blockchain.event.register('contextChanged', (context) => {
dispatch(resetProxyDeployments())
if (!context.startsWith('vm')) getNetworkProxyAddresses(plugin, dispatch)
setFinalContext(plugin, dispatch)
@ -117,6 +119,25 @@ export const setupEvents = (plugin: RunTab, dispatch: React.Dispatch<any>) => {
plugin.event.register('cleared', () => {
dispatch(clearRecorderCount())
})
plugin.on('injected', 'accountsChanged', (accounts: Array<string>) => {
const accountsMap = {}
accounts.map(account => { accountsMap[account] = shortenAddress(account, '0')})
dispatch(fetchAccountsListSuccess(accountsMap))
})
plugin.on('blockchain', 'contextChanged', () => {
fillAccountsList(plugin, dispatch)
})
plugin.on('blockchain', 'transactionExecuted', () => {
updateInstanceBalance(plugin)
})
setInterval(() => {
fillAccountsList(plugin, dispatch)
updateInstanceBalance(plugin)
}, 30000)
}
const broadcastCompilationResult = async (compilerName: string, plugin: RunTab, dispatch: React.Dispatch<any>, file, source, languageVersion, data, input?) => {
@ -159,7 +180,7 @@ const getCompiledContracts = (compiler) => {
return contracts
}
export const resetAndInit = (plugin: RunTab) => {
export const resetAndInit = async (plugin: RunTab) => {
plugin.blockchain.resetAndInit(plugin.config, {
getAddress: (cb) => {
cb(null, plugin.REACT_API.accounts.selectedAccount)

@ -2,7 +2,7 @@
import React from 'react'
import { RunTab } from '../types/run-tab'
import { resetAndInit, setupEvents } from './events'
import { createNewBlockchainAccount, fillAccountsList, setExecutionContext, signMessageWithAddress } from './account'
import { createNewBlockchainAccount, setExecutionContext, signMessageWithAddress } from './account'
import { clearInstances, clearPopUp, removeInstance, setAccount, setGasFee, setMatchPassphrasePrompt,
setNetworkNameFromProvider, setPassphrasePrompt, setSelectedContract, setSendTransactionValue, setUnit,
updateBaseFeePerGas, updateConfirmSettings, updateGasPrice, updateGasPriceStatus, updateMaxFee, updateMaxPriorityFee, updateScenarioPath } from './actions'
@ -25,12 +25,8 @@ let plugin: RunTab, dispatch: React.Dispatch<any>
export const initRunTab = (udapp: RunTab) => async (reducerDispatch: React.Dispatch<any>) => {
plugin = udapp
dispatch = reducerDispatch
setupEvents(plugin, dispatch)
resetAndInit(plugin)
setupEvents(plugin, dispatch)
setInterval(() => {
fillAccountsList(plugin, dispatch)
updateInstanceBalance(plugin)
}, 1000)
}
export const setAccountAddress = (account: string) => setAccount(dispatch, account)

@ -60,7 +60,7 @@ export class Blockchain extends Plugin<any, any> {
removeProvider(name: any): void;
/** Listen on New Transaction. (Cannot be done inside constructor because txlistener doesn't exist yet) */
startListening(txlistener: any): void;
resetEnvironment(): void;
resetEnvironment(): Promise<void>;
/**
* Create a VM Account
* @param {{privateKey: string, balance: string}} newAccount The new account to create

@ -4,7 +4,7 @@ declare class InjectedProvider {
executionContext: any;
getAccounts(cb: any): any;
newAccount(passwordPromptCb: any, cb: any): void;
resetEnvironment(): void;
resetEnvironment(): Promise<void>;
getBalanceInEther(address: any, cb: any): void;
getGasPrice(cb: any): void;
signMessage(message: any, account: any, _passphrase: any, cb: any): void;

@ -5,7 +5,7 @@ declare class NodeProvider {
config: any;
getAccounts(cb: any): any;
newAccount(passwordPromptCb: any, cb: any): any;
resetEnvironment(): void;
resetEnvironment(): Promise<void>;
getBalanceInEther(address: any, cb: any): void;
getGasPrice(cb: any): void;
signMessage(message: any, account: any, passphrase: any, cb: any): void;

@ -3,7 +3,7 @@ declare class VMProvider {
constructor(executionContext: any);
executionContext: any;
getAccounts(cb: any): void;
resetEnvironment(): void;
resetEnvironment(): Promise<void>;
accounts: any;
RemixSimulatorProvider: any;
web3: any;

Loading…
Cancel
Save