6

Why the usual way to create a contract with evm opcodes use add and mload, for example:

bytes memory bytecode = hex"600580600c6000396000b800602a600052b8";
...
assembly {
    _address := create(0, add(bytecode, 0x20), mload(bytecode))
}

I can't understand why adds 0x20 to the initial position and why mload(bytecodes) returns the size of bytecodes. Is someone can point me doc related I'll appreciate.

Thanks.

1 Answer 1

8

This is because memory variables are treated as pointers from in solidity assembly - and that pointer points to the start in memory of the variable. The way arrays are stored in memory in Solidity is with the first 0x20 (32) bytes being the length of the data in the array, and then the actual data directly following, which is why add(bytecode, 0x20) is needed to get the start of the actual data in bytecode . Since the first 0x20 bytes are the length of the array, mload(bytecode) grabs the length of the bytecode to store.

Edit: To fully understand this, you should read through the Assembly as well as Miscellaneous (mainly the details about storage/memory layout) sections of the Solidity Docs

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.