Solidity Tutorial – Execute Raw Bytecode in EVM

bytecodeevmsolidity

Suppose, I have the following bytecode (0x610101610102016000526001601ff3) that pushes two numbers to the stack, adds them and returns the value.

Now I want to write a function in Solidity that will take this bytecode as input and return the final result (i.e., the final stack, memory, and storage contents after the execution inside EVM). How can I write this function? Is it possible to do so (for example – using the solidity assembly)? Please suggest. Thanks in advance.

Best Answer

Surely, you may do this. Here are high-level steps:

  1. To the end of your bytecode append a few additional opcodes that copy stack and storage content into memory and return them together with memory content.
  2. Prepend you bytecode with a simple constructor that will just deploy your bytecode as a contract.
  3. Deploy modified bytecode and obtain deployed smart contract address.
  4. Call just deployed smart contract. This effectively will execute original bytecode and return stack, storage, and memory content after the execution.

The challanges here are how to determine stack depth and how to find out modified storage keys. May you make the bytecode being executed to follow some convention about these things, such as leave stack depth and storage keys on the stack after execution?

If you need to execute each bytecode only once, you may add SELFDESTRUCT opcode before RETURN in order to destroy the smart contract after the call.

Related Topic