2

I'm making a simple storage contract in stylus, but I'm confused as to why I can't import alloc like I can other imports.

I have two kinds of imports

// the extern
extern crate alloc;

// The classic use import
use stylus_sdk::{
    alloy_primitives::U256,
    prelude::{entrypoint, external, sol_storage},
};

But the following doesn't compile for me:

use std::alloc

Because it gives me errors with entrypoint

sol_storage! {
    #[entrypoint]
    pub struct SimpleStorage {
        uint256 my_favorite_number;
    }
}
error[E0433]: failed to resolve: could not find `vec` in `alloc`
  --> src/main.rs:20:5
   |
20 |     #[entrypoint]
   |     ^^^^^^^^^^^^^ could not find `vec` in `alloc`

2 Answers 2

1

In Edition 2015 of Rust, extern crate was used to import crates. However, that is no longer necessary. The "sysroot" crates are an exception though, and alloc is one of them. That is why you need to import it with an extern crate statement.


Why do you need to import alloc with stylus-sdk? Well, the nature of the Stylus' WASM VM makes it a very constrained environment for running programs, which means that we must reduce binary size as much as possible. In this environment, it is useful to use no_std.

The authors of stylus-sdk have predicted this beforehand and, thus, use alloc directly without importing std. This enables users to use both std and no_std as they see fit and falls back to no_std, which should be the common case.


std::vec is the place where Vec and its associated structs live.

To use Vec in a no_std environment, you'd use alloc::vec::Vec.

0

Items in the alloc crate are usually accessed via re-exports in the std crate. If you are working with a no_std crate that supports allocation, then you may need to explicitly import alloc.

so just use the std::vec or you need extern crate alloc;

excption in No more extern crate

1
  • I don't follow. What is std::vec? Commented Oct 11, 2023 at 10:55

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.