Expand description
Standard library for use in Gear programs.
This library should be used as a standard library when writing Gear
programs. Compared to gcore
crate,
this library provides higher-level primitives that allow you to develop more
complex dApps. Choose this library if you are ready to spend more gas but
receive refined code.
gstd
crate provides many advanced tools for a developer, such as
asynchronous programming primitives, arbitrary types encoding/decoding,
providing convenient instruments for creating programs from programs, etc.
§Minimum supported Rust version
This crate requires Rust >= 1.81 due to the implementation of the panic handler in the stable version.
§Crate features
§Default features:
panic-message
§Panic handler profiles
We currently use the following format for panic messages from Rust code:
panicked with '{message}'[ at '{location}']
. Also Panic occurred:
will be added to the beginning of the panic message by our core-backend.
So the final panic message looks like this:
Panic occurred: panicked with '{message}'[ at '{location}']
.
You can configure which panic handler profile you need by specifying one of the following functions:
panic-handler
— When enabled, a minimal panic handler is provided by this crate. Instead of a panic message,<unknown>
is displayed.panic-message
(enabled by default) — When enabled, a panic handler will also display a panic message.panic-location
— When enabled, a panic handler will also display a panic message and location. This function is not recommended for use in production environment because it displays the code path.
For example, if you don’t use the panic-location
feature, the compiler
will remove all locations such as /home/username/dapp/src/lib.rs:1:2
from the binary. The size of program will be reduced and
/home/username/...
information will not be included in the binary.
§Nightly features
The final binary gets additional optimizations when using the nightly compiler.
nightly
— Enables all features below. These features depend on unstable Rust API and require nightly toolchain.oom-handler
— When enabled, an OOM error handler is provided. Relies onalloc_error_handler
.
§Additional features
ethexe
— Disables unsupported syscalls and their calls for executing on ethexe.debug
— Enables debug logging; this heavily impacts gas cost and is therefore disabled by default.
§Examples
Decode input payload using a custom type:
#![no_std]
use gstd::{msg, prelude::*};
#[derive(Decode, Encode, TypeInfo)]
#[codec(crate = gstd::codec)]
#[scale_info(crate = gstd::scale_info)]
struct Payload {
question: String,
answer: u8,
}
#[unsafe(no_mangle)]
extern "C" fn handle() {
let payload: Payload = msg::load().expect("Unable to decode payload");
if payload.question == "life-universe-everything" {
msg::reply(payload.answer, 0).expect("Unable to reply");
}
}
Asynchronous program example.
It sends empty messages to three addresses and waits for at least two
replies (“approvals”) during initialization. When invoked, it handles only
PING
messages and sends empty messages to the three addresses, and waits
for just one approval. If approval is obtained, the program replies with
PONG
.
# const _: &'static str = stringify! {
#![no_std]
# };
use futures::future;
use gstd::{msg, prelude::*, ActorId};
static mut APPROVERS: [ActorId; 3] = [ActorId::zero(); 3];
#[derive(Debug, Decode, TypeInfo)]
#[codec(crate = gstd::codec)]
#[scale_info(crate = gstd::scale_info)]
pub struct Input {
pub approvers: [ActorId; 3],
}
#[gstd::async_init]
async fn init() {
let payload: Input = msg::load().expect("Failed to decode input");
unsafe { APPROVERS = payload.approvers };
let mut requests: Vec<_> = unsafe { APPROVERS }
.iter()
.map(|addr| msg::send_bytes_for_reply(*addr, b"", 0, 0))
.collect::<Result<_, _>>()
.unwrap();
let mut threshold = 0;
while !requests.is_empty() {
let (.., remaining) = future::select_all(requests).await;
threshold += 1;
if threshold >= 2 {
break;
}
requests = remaining;
}
}
#[gstd::async_main]
async fn main() {
let message = msg::load_bytes().expect("Failed to load payload bytes");
if message != b"PING" {
return;
}
let requests: Vec<_> = unsafe { APPROVERS }
.iter()
.map(|addr| msg::send_bytes_for_reply(*addr, b"", 0, 0))
.collect::<Result<_, _>>()
.unwrap();
_ = future::select_all(requests).await;
msg::reply(b"PONG", 0).expect("Unable to reply");
}
# fn main() {}
Re-exports§
pub use prelude::*;
Modules§
- critical
- Critical hook that guarantees code section execution.
- errors
- Type definitions and helpers for error handling.
- exec
- Utility functions related to the current execution context or program execution flow.
- ext
- Extensions for additional features.
- msg
- Messaging API for Gear programs.
- prelude
- The
gstd
default prelude. Re-imports defaultstd
modules and traits.std
can be safely replaced togstd
in the Rust programs. - prog
- Functions and helpers for creating programs from programs.
- sync
- Data access synchronization objects.
- util
- Utility functions.
Macros§
- actor_
id - Macro to declare
ActorId
from hexadecimal and ss58 format. - bail
- Unwrap
Result<T, E>
toT
if it isOk(T)
or panic with the provided message if the result isErr(E)
. - dbg
- Prints and returns the value of a given expression for quick and dirty debugging.
- debug
- Add a debug message to the log.
- heap_
debug - Add a debug message to the log.
- static_
mut - Get mutable reference to
static mut
. - static_
ref - Get shared reference to
static mut
.
Structs§
- ActorId
- Program (actor) identifier.
- CodeId
- Code identifier.
- Config
- The set of broadly used internal parameters.
- EnvVars
- Current version of execution settings.
- GasMultiplier
- Type representing converter between gas and value.
- Message
Id - Message identifier.
- Percent
- Basic struct for working with integer percentages allowing values greater than 100.
- Reservation
- Stores additional data along with
ReservationId
to track its state. - Reservation
Id - Reservation identifier.
- Reservations
- Reservation manager.
- Ss58
Address - Represents SS58 address.
Constants§
- SYSTEM_
RESERVE - Constant declaring default
Config::system_reserve()
in case of not “ethexe” feature.
Traits§
- Reservation
IdExt - Reservation identifier extension.
Functions§
- handle_
reply_ with_ hook - Default reply handler.
- handle_
signal - Default signal handler.
- message_
loop - The main asynchronous message handling loop.
Type Aliases§
- Block
Count - Represents block count type.
- Block
Number - Represents block number type.
- Gas
- Represents gas type.
- Value
- Represents value type.
Attribute Macros§
- async_
init - Mark async function to be the program initialization method.
- async_
main - Mark the main async function to be the program entry point.