10

I've heard that it is a bad idea to use Rust's String type in an ink! smart contract.

Why is this so? And what is your recommendation to use instead for typical use cases of String ‒ so parsing input data, storing textual descriptions of things, etc.?

3 Answers 3

16

The reason why we discourage usage of String is because those are regularly meant to display user facing text. A contract should only contain data that absolutely must be subject to consensus: Everything done within a contract is subject to a fee and string manipulation is expensive.

It is a common misconception that people think that users should directly interact with contracts and then try to output error messages and help texts. This is the job of your front end (typically a web app). For example, you could output numeric error codes and map those to strings in your front end.

12

To add to Alex' answer:

String processing comes with a lot of overhead (e.g. support for UTF-8 operations). For smart contracts it's important that they are small in terms of size, this reduces the gas fees for users as well as the throughput a blockchain can achieve when multiple contracts are called in one block.

By using String's the entire code bloat for being able to handle them has to be included in the smart contract, thus making them way bigger than they need to be.

If you're in need for e.g. parsing JSON then that's something that should definitely be done on the side of the user interface/client/Dapp and only the result of the parsing should be submitted.

If you're really in need to store something human readable you could make it a Vec<u8> instead of a String ‒ thus avoiding the inclusion of any String processing overhead.

If you're really really in need of String, then ink! exposes it via the crate ink_prelude as ink_prelude::String (see https://paritytech.github.io/ink/ink_prelude/string/index.html).

4

Generally with smart contracts you can construct them such that rather than using an unbounded and potentially very costly in gas string, one can store the hash of that string which is a fixed size no matter how long the original string is. The gas costs that way are fixed and more predictable leading to a better user experience.

1

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.