Search code examples
rustsubstrate

How to import substrate_primitives in order to use sr25519?


I have the following dependencies in my Cargo.toml file:

[package]
name = "api-client-tutorial"
version = "0.1.0"
authors = ["Supercomputing Systems AG <info@scs.ch>"]
edition = "2018"

[dependencies]
substrate-api-client = { git = "https://github.com/scs/substrate-api-client.git" }
codec = { package = "parity-scale-codec", features = ["derive"], version = "1.0.0", default-features = false }

[dependencies.primitives]
git = "https://github.com/paritytech/substrate"
rev = "3bf9540e72df5ecb3955845764dfee7dcdbb26b5"
package = "substrate-primitives"

[dependencies.keyring]
git = "https://github.com/paritytech/substrate"
rev = "3bf9540e72df5ecb3955845764dfee7dcdbb26b5"
package = "substrate-keyring"

I am unsure of the difference between dependencies section and dependencies.primitives section, but the package substrate-primitives is included in the primitives section.

I have seen that substrate_primitives has the module sr25519 I need to use, but when I try to import it in my code:

use substrate_api_client::{Api, node_metadata};
use substrate_primitives::sr25519;
fn main() {
    // instantiate an Api that connects to the given address
    let url = "127.0.0.1:9944";
    // if no signer is set in the whole program, we need to give to Api a specific type instead of an associated type
    // as during compilation the type needs to be defined.
    let api = Api::<sr25519::Pair>::new(format!("ws://{}", url));

    let meta = api.get_metadata();
    println!("Metadata:\n {}", node_metadata::pretty_format(&meta).unwrap());
}

I get the following error:

unresolved import `substrate_primitives`

use of undeclared type or module `substrate_primitives`rustc(E0432)
main.rs(2, 5): use of undeclared type or module `substrate_primitives`

How do I import sr25519 so that I can use the following line in my code?

let api = Api::<sr25519::Pair>::new(format!("ws://{}", url));

Solution

  • The difference between tables under [dependencies] and the [dependencies.primitives] table is that the table for the primitives dependency is not inlined. You could also just inline the primitives dependency and put it under [dependencies] like that:

    primitives = { git = "https://github.com/paritytech/substrate", rev = "3bf9540e72df5ecb3955845764dfee7dcdbb26b5", package = "substrate-primitives" }
    

    The toml documentation can give you more details on tables and inline tables.

    Regarding your problem. You cannot import the crate like that, because it is renamed to primitives. The package field specifies the real name of the dependency and the table name defines the new name which is used to import it inside your project. For details have a look at the cargo documentation.

    Your import should therefore look like this: use primitives::sr25519;