3

I am writing a contract in pure Yul and I want to return a string from a function.

Imagine the ABI as:

function getString() view returns (string memory);

But in Yul, how can I do this?

1 Answer 1

5

Okay figured it out. Here is how:

Basic example of how the function would work (with hardcoded string, point is to show how the memory should be prepared) - I am not showing the surrounding code, just the key functionality:


function getString() {
    mstore(0x00, 0x20) # you need to say where in *the return data* (btw. not relative to your own memory) the string starts (aka where it's length is stored - here it's 0x20)
    mstore(0x20, 0xe) # then the length of the string, let's say it's 14 bytes
    mstore(0x40, 0x737461636B6F766572666C6F7721000000000000000000000000000000000000) # the string to return in hex
    return(0, 0x60)
}

Note: For the string: It's important to pad it with 0's on the right, because or else the bytes will all sit in the right side of the 32 byte word. If the string is longer than 32 bytes, you need to keep mstore()'ing until the entire string is in memory (and still of course reflect the full length in bytes in the length part).

If you leave out that initial 32 bytes of 0's (mstore(0x00, 0x20)) it won't work btw.

3
  • thanks for your answer, spent days trying to figure out the right way to return string/bytes using YUL, I thought the right return format of string/bytes should be 2 parts: size, and the data itself. why the additional part: mstore(0x00, 0x20)? would be appreciated if you can provide some link for me to further learn where am i missing.
    – DiveInto
    Commented Aug 19 at 16:42
  • it is abi.encoding rule for dynamic types, which includes 3 parts: offset, length, and data docs.soliditylang.org/en/latest/…
    – DiveInto
    Commented Aug 21 at 14:47
  • that's right, I cover that here as well: youtube.com/watch?v=upVloLUw5Z0 Commented Sep 17 at 0:29

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.