Raw string literals
String literals produce a binary slice where each character is encoded with its ASCII character number:Compile-time functions
Several functions operate on constant strings and string literals at compile time. The produced values are embedded in the contract as constants.Embed hexadecimal data
To embed hexadecimal binary data, usestringHexToSlice("..."):
Embed human-readable address strings
Theaddress("...") function inserts a constant slice containing a standard internal contract address:
Concatenate string literals
There are no compile-time means to concatenate string literals. Instead, concatenation can be performed at runtime via a builder:Serialization
Plain slices cannot be serialized directly: they require a fixed-width type or custom serialization rules. Similarly, string-like data must use an explicit encoding to be stored on-chain or returned from contracts.Fixed-size strings via bitsN
If a string size is fixed and does not exceed 1023 bits, use fixed-size encodings: bitsN or bytesN, where N cannot go beyond 1023 or 127, respectively.
Snake strings
For arbitrary strings, the so-called snake string or tail string encoding is often used. Snake encoding works by storing a portion of data in the current cell and storing the rest in the first ref cell, recursively. The process repeats until all the data is stored in a chain of cells. For instance, a stringxxxxyyyyzzzz can be split into three parts and stored as a snake string:
MyTailString is a type alias to RemainingBitsAndRefs, which is a slice that holds the remainder of the data when read. On-chain decoding of such strings does not require iteration over nested references.
Variable-length encoding
Encoding of variable-length strings can also be implemented manually using a type alias overslice and its custom serializers.
For example, short strings like "abcd" can be stored as 8 bits for N, where N is the string length, followed by N bits of data:
ShortString can be used as a regular type and enjoy auto-serialization: