Messages
The SC framework supports message interpolation in a variety of situations.
The mechanism makes full use of managed types, and does not require memory allocation on the heap.
It resembles the standard message formatting in Rust, but it does not have all the features and is a completely separate implementation.
To see these features in action, we have an example contract just for that.
Errors
The most common place to see message interpolation is in the error messages. These messages will be seen in the explorer and tools if a transaction fails.
sc_panic!
Whenever encountered, it stops execution immediately, and returns the given error message. Also note that for all errors originating in the smart contract, the status code is "4".
The macro simplifies the process of throwing exceptions with custom error messages. It works with formatted messages with arguments, and with static messages without arguments.
sc_panic!("Formatted error message with arguments: {}", arg); // message with argument
sc_panic!("Static error message"); // static messages
require!
require!
is a macro used to enforce preconditions by checking whether an expression evaluates to true. If the expression evaluates to false, it will trigger a panic with a specific error message. It is very useful when validating pre-conditions.
require!(expression, "formatted error message with argument: {}", arg); // error message with argument
require!(expression, "error message"); // static error messages
Formatting string
We might want to interpolate a string for other uses than throwing an error, such as returning it or saving it to storage.