s.Takahashi
s.Takahashi

Reputation: 479

How do I save a string value on Substrate's smart contract platform, ink?

  1. I initially tried the implementation as taught in this question. (How can I save string value on Substrate)
  2. However, an error occurred in relation to "ink_abi" and the struct could not be defined.
  3. Looking at the latest "ink! example"(), I tried to copy it because the struct was defined, but the following command does not work. (https://github.com/paritytech/ink/blob/master/examples/runtime-storage/lib.rs)
cargo +nightly generate-metadata
  1. How can I save the string data to the blockchain with "substrate ink!"?
  2. I would like to see a sample source if available.

Upvotes: 4

Views: 1135

Answers (2)

user2465214
user2465214

Reputation: 56

Use ink_prelude::string::String

#![cfg_attr(not(feature = "std"), no_std)]
use ink_lang as ink;

#[ink::contract]
mod foo {
    use ink_prelude::string::String;

    // ...
}

And don't forget to add ink_prelude to your [dependencies] section in your .toml

see: https://paritytech.github.io/ink/ink_prelude/string/struct.String.html

Upvotes: 3

Shawn Tabrizi
Shawn Tabrizi

Reputation: 12434

In ink! you can directly use the String type.

Here is a simple implementation of an ink! contract doing this with tests (modified from the incrementer example:

#![cfg_attr(not(feature = "std"), no_std)]

use ink_lang as ink;

#[ink::contract(version = "0.1.0")]
mod basic_string {
    #[ink(storage)]
    struct BasicString {
        value: String,
    }

    impl BasicString {
        #[ink(constructor)]
        fn new(init_value: String) -> Self {
            Self { value: init_value }
        }

        #[ink(constructor)]
        fn default() -> Self {
            Self::new(Default::default())
        }

        #[ink(message)]
        fn set(&mut self, new: String) {
            self.value = new;
        }

        #[ink(message)]
        fn get(&self) -> String {
            self.value.clone()
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn default_works() {
            let contract = BasicString::default();
            assert_eq!(contract.get(), "");
        }

        #[test]
        fn it_works() {
            let mut contract = BasicString::new("Hello World!".into());
            assert_eq!(contract.get(), "Hello World!");
            contract.set("Goodbye!".into());
            assert_eq!(contract.get(), "Goodbye!");
        }
    }
}

Upvotes: 2

Related Questions