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?
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.
mstore(0x00, 0x20)
? would be appreciated if you can provide some link for me to further learn where am i missing.