Is there anyway to access the runtime code of a function from its contract? Using assembly may be?


  • Please provide more details - are you trying to access the bytecode onchain or to decompile/debug a contract? Commented May 28, 2022 at 18:49

1 Answer 1


Yes, you can do that with assembly using the codecopy built-in function or extcodecopy (see the documentation).

Here is an example of a function returning the required portion of the current contract's byte code : _length bytes starting from _pc, with proper memory management :

pragma solidity >=0.8.14;

contract Example {

    function aFunction(uint256 _length, uint256 _pc) public view returns (bytes memory code) {
        assembly {
            // Allocate memory for the byte array
            code := mload(0x40)
            mstore(0x40, add(code, add(0x40, mul(0x20, div(_length, 0x20)))))

            // Set the length of the byte array
            mstore(code, _length)

            // Copy contract's code to the byte array data
            codecopy(add(code, 0x20), _pc, _length)

Compiling this contract with solidity 0.8.14 on default settings, this function's bytecode is :


Which is 0x26 (38) bytes long and starts at position 0x60 (96) in the contract's code, you can check it with this tool if you are interested. Calling aFunction(0x26, 0x60) makes it return its own bytecode : 0x5b60606040519050602083046020026040018101604052828152828260208301399291505056

Keep in mind that a contract's code is read only. Any modification must be done in memory, this is what deployement bytecodes do to setup immutable variables for example.

I hope that answers your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.