EVM – Can the Ethereum Virtual Machine Execute Code from Memory?

evmmemorystatic-call

To my understanding address(addr).code and memory[...] are in different places and since code memory is read-only, a usual call doesn't seem to be able to achieve this, but is there any other way to e.g. execute code passed as function parameter?

function execute(bytes calldata _code) {
    magically_call(_code)
}

I mean theoretically one could implement an EVM bytecode interpreter, but that would be quite an expensive contract…

Best Answer

Amplifying @Ismael's answer,you could achieve the effect by deploying contracts with the code to run, and running in a proxy that accepts a contract address and uses delegate call to execute the arbitrary function. There would be a deployment cost for each arbitrary code instance and, of course, the main contract would plainly do literally anything, casting more than a little doubt on any assurances about what it actually does.

Check out "diamond pattern" for inspiration.

Hope it helps.

Related Topic