In Sway, strings are statically-sized, which means you must define the size of the string beforehand. Statically-sized strings are represented using the str[x]
syntax, where x
indicates the string's size.
This guide explains how to create and interact with statically-sized strings while using the SDK.
// Sway str[2]
const stringSize2 = 'st';
// Sway str[8]
const stringSize8 = 'fuel-sdk';
When a contract method accepts and returns a str[8]
, the corresponding SDK wrapper method will also take and return a string of the same length. You can pass a string to the contract method like this:
const { value } = await contract.functions.echo_str_8('fuel-sdk').simulate();
expect(value).toEqual('fuel-sdk');
When working with statically-sized strings, ensure that the input and output strings have the correct length to avoid erroneous behavior.
If you pass a string that is either too long or too short for a contract method, the call will fail like this:
const longString = 'fuel-sdk-WILL-THROW-ERROR';
await expect(async () => contract.functions.echo_str_8(longString).call()).rejects.toThrowError(
'Value length mismatch during encode'
);
const shortString = 'THROWS';
await expect(async () =>
contract.functions.echo_str_8(shortString).call()
).rejects.toThrowError('Value length mismatch during encode');