Crate concordium_std[][src]

Expand description

This library provides the core API that can be used to write smart contracts for the Concordium blockchain. It aims to provide safe wrappers around the core primitives exposed by the chain and accessible to smart contracts.

By default the library will be linked with the std crate, the rust standard library, however to minimize code size this library supports toggling compilation with the #![no_std] attribute via the feature std which is enabled by default. Compilation without the std feature requires a nightly version of rust.

To use this library without the std feature you have to disable it, which can be done, for example, as follows.

[dependencies.concordium-std]
default-features = false

In your project’s Cargo.toml file.

The library is meant to be used as a standard library for developing smart contracts. For this reason it re-exports a number of definitions from other libraries.

Global allocator.

Importing this library has a side-effect of setting the allocator to wee_alloc which is a memory allocator aimed at small code footprint. This allocator is designed to be used in contexts where there are a few large allocations up-front, and the memory is afterwards used by the program without many further allocations. Frequent small allocations will have bad performance, and should be avoided.

In the future it will be possible to opt-out of the global allocator via a feature.

Panic handler

When compiled without the std feature this crate sets the panic handler so that it terminates the process immediately, without any unwinding or prints. Concretely, when compiled to the wasm32 target panic boils down to the unreachable instruction, which triggers a runtime failure, aborting execution of the program.

Build for generating a module schema

WARNING Building with this feature enabled is meant for tooling, and the result is not intended to be deployed on chain.

This library provides a way to automate the building of smart contract module schema, by allowing the contract to be built exporting getter functions for the concordium_contracts_common::schema::Type of Types for contract state and parameters. This special build is only intended to be used for generating the schema and is not meant to be deployed, since the build exports functions that do not conform to the expected API of smart contracts. The build is enabled by setting the feature build-schema.

Note This feature is used by cargo-concordium, when building with schema and for most cases this feature should not be set manually.

Build for testing in Wasm

WARNING Building with this feature enabled is meant for tooling, and the result is not intended to be deployed on chain.

The macros #[concordium_test] and #[concordium_cfg_test] are reduced to #[test] and #[cfg(test)] unless the wasm-test feature is enabled.

With the wasm-test feature enabled, the #[concordium_test] macro exports the test as an extern function, allowing tools such as cargo-concordium to call the test functions directly, when compiled to Wasm. Without the feature it falls back to #[test].

With the ‘wasm-test’ feature enabled, the #[concordium_cfg_test] macro allows the annotated code to be included in the build. Without the feature, it falls back to #[cfg(test)].

Note This feature is used by cargo-concordium, when building for testing and for most cases this feature should not be set manually.

Traits

Most of the functionality for interacting with the host is abstracted away by the traits

  • HasParameter for accessing the contract parameter
  • HasCommonData for accessing the data that is common to both init and receive methods
  • HasInitContext for all the context data available to the init functions (note that this includes all the common data)
  • HasReceiveContext for accessing all the context data available to the receive functions (note that this includes all the common data)
  • HasLogger for logging data during smart contract execution
  • HasPolicy for accessing the policy of the sender, either of the init or receive method
  • HasContractState for operations possible on the contract state.

These are provided by traits to make testing easier. There are two main implementations provided for these traits. One provided by so-called host functions, which is the implementation that is used by Concordium nodes when contracts are executed on the chain, or when tested via cargo-concordium.

The second implementation is on types in the test_infrastructure module, and is intended to be used for unit-testing together with the concordium_test infrastructure.

Signalling errors

On the Wasm level Contracts can signal errors by returning a negative i32 value as a result of either initialization or invocation of the receive method. To make error handling more pleasant we provide the Reject structure. The result type of a contract init or a receive method is assumed to be of the form Result<_, E> where Reject: From<E>.

The intention is that smart contract writers will write their own custom, precise, error types and either manually implement Reject: From<E> for their type E, or use the Reject macro which supports the common use cases.

In addition to the custom errors that signal contract-specific error conditions this library provides some common error cases that most contracts will have to handle and their conversions to Reject. These are

VariantError code
()i32::MIN + 1 (-2147483647)
ParseErrori32::MIN + 2 (-2147483646)
LogError::Fulli32::MIN + 3
(-2147483645)
Malformed)i32::MIN + 4 (-2147483644)
MissingInitPrefix](./enum.LogError.html#variant.Malformed)i32::MIN + 5
(-2147483643)
NewContractNameError.html#variant.TooLong)i32::MIN + 6 (-2147483642)
NewContractNameError::ContainsDot(./enum.NewContractNameError.html#
variant.ContainsDot)i32::MIN + 9 (-2147483639)
NewContractNameError::InvalidCharacters(./enum.NewContractNameError.
html#variant.InvalidCharacters)i32::MIN + 10 (-2147483638)
NewReceiveNameError::MissingDotSeparator(./enum.NewReceiveNameError.
html#variant.MissingDotSeparator)i32::MIN + 7 (-2147483641)
NewReceiveNameError::TooLong(./enum.NewReceiveNameError.html#variant.
TooLong)i32::MIN + 8 (-2147483640)
InvalidCharacters](./enum.NewReceiveNameError.html#variant.
InvalidCharacters)i32::MIN + 11 (-2147483637)
/struct.NotPayableError.html)i32::MIN + 12 (-2147483636)

Other error codes may be added in the future and custom error codes should not use the range i32::MIN to i32::MIN + 100.

Modules

Currently defined attributes possible in a policy.

Chain constants that impose limits on various aspects of smart contract execution.

Re-export.

Re-export.

Re-export.

Re-export.

Re-export.

Types related to contract schemas. These are optional annotations in modules that allow the users of smart contracts to interact with them in a way that is better than constructing raw bytes as parameters.

The test infrastructure module provides alternative implementations of HasInitContext, HasReceiveContext, HasParameter, HasActions, and HasContractState traits intended for testing.

Macros

The bail macro can be used for cleaner error handling. If the function has result type Result invoking bail will terminate execution early with an error. If an argument is supplied, this will be used as the error, otherwise it requires the type E in Result<_, E> to implement the Default trait.

The claim macro is used for testing as a substitute for the assert macro. It checks the condition and if false it reports back an error. Used only in testing.

Ensure the first two arguments are equal, just like assert_eq!, otherwise reports an error. Used only in testing.

Ensure the first two arguments are not equal, just like assert_ne!, otherwise reports an error. Used only in testing.

The ensure macro can be used for cleaner error handling. It is analogous to assert, but instead of panicking it uses bail to terminate execution of the function early.

Variants of ensure for ease of use in certain contexts.

Ensure the first two arguments are not equal, using bail otherwise.

The fail macro is used for testing as a substitute for the panic macro. It reports back error information to the host. Used only in testing.

Structs

Address of an account, as raw bytes.

Actions that can be produced at the end of a contract execution. This type is deliberately not cloneable so that we can enforce that and_then and or_else can only be used when more than one event is created.

The type of amounts on the chain

Tag of an attribute. See the module attributes for the currently supported attributes.

A type representing the attributes, lazily acquired from the host.

Chain metadata accessible to both receive and init methods.

Address of a contract.

A contract name. Expected format: “init_<contract_name>”.

A type representing the constract state bytes.

Add offset tracking inside a data structure.

Duration of time in milliseconds.

A type representing the logger.

Error triggered when a non-zero amount of GTU is sent to a contract init or receive function that is not marked as payable.

A contract name (owned version). Expected format: “init_<contract_name>”.

A receive name (owned version). Expected format: “<contract_name>.<func_name>”.

A type representing the parameter to init and receive methods.

Zero-sized type to represent an error when reading bytes and deserializing.

An iterator over policies using host functions to supply the data. The main interface to using this type is via the methods of the Iterator and ExactSizeIterator traits.

Policy on the credential of the account.

A receive name. Expected format: “<contract_name>.<func_name>”.

An error message, signalling rejection of a smart contract invocation. The client will see the error code as a reject reason; if a schema is provided, the error message corresponding to the error code will be displayed. The valid range for an error code is from i32::MIN to -1.

Re-export.

Timestamp represented as milliseconds since unix epoch.

Re-export.

Enums

Either an address of an account, or contract.

An error indicating why parsing of an amount failed. Since amount parsing is typically a user-facing activity this is fairly precise, so we can notify the user why we failed, and what they can do to fix it.

Errors that can occur during logging.

This is the equivalent to the SeekFrom type from the rust standard library, but reproduced here to avoid dependency on std::io.

Constants

Size of an account address when serialized in binary. NB: This is different from the Base58 representation.

Traits

The Deserial trait provides a means of reading structures from byte-sources (Read).

The DeserialCtx trait provides a means of reading structures from byte-sources (Read) using contextual information. The contextual information is:

Analogue of the expect_err methods on Result, but useful in a Wasm setting.

Analogue of the expect_none methods on Option, but useful in a Wasm setting.

Analogue of the expect methods on types such as Option, but useful in a Wasm setting.

A more convenient wrapper around Deserial that makes it easier to write deserialization code. It has a blanked implementation for any read and serialize pair. The key idea is that the type to deserialize is inferred from the context, enabling one to write, for example,

An object that can serve to construct actions.

Objects which can access chain metadata.

Common data accessible to both init and receive methods.

A type that can serve as the contract state type.

Types which can act as init contexts.

Objects which can serve as loggers.

Objects which can access parameters to contracts.

A type which has access to a policy of a credential. Since policies can be large this is deliberately written in a relatively low-level style to enable efficient traversal of all the attributes without any allocations.

Types which can act as receive contexts.

The Read trait provides a means of reading from byte streams.

The Seek trait provides a cursor which can be moved within a stream of bytes. This is essentially a copy of std::io::Seek, but avoiding its dependency on std::io::Error, and the associated code size increase.

The Serial trait provides a means of writing structures into byte-sinks (Write).

The SerialCtx trait provides a means of writing structures into byte-sinks (Write) using contextual information. The contextual information is:

The Serialize trait provides a means of writing structures into byte-sinks (Write) or reading structures from byte sources (Read).

Add optimized unwrap behaviour that aborts the process instead of panicking.

The Write trait provides functionality for writing to byte streams.

Functions

Read a HashMap as a list of key-value pairs given some length.

Read a HashSet as a list of keys, given some length. NB: This ensures there are no duplicates.

Read a BTreeMap as a list of key-value pairs given some length. NB: This ensures there are no duplicates, hence the specialized type. Moreover this will only succeed if keys are listed in order.

Read a BTreeMap as a list of key-value pairs given some length. Slightly faster version of deserial_map_no_length as it is skipping the order checking

Read a BTreeSet as a list of keys, given some length. NB: This ensures there are no duplicates, hence the specialized type. Moreover this will only succeed if keys are listed in order.

Read a BTreeSet as an list of key-value pairs given some length. Slightly faster version of deserial_set_no_length as it is skipping the order checking. The only check that is made to the set is that there are no duplicates.

Read a vector given a length.

Dual to to_bytes.

Wrapper for HasActions::send_raw, which automatically serializes the parameter. Note that if the parameter is already a byte array or convertible to a byte array without allocations it is preferrable to use send_raw. It is more efficient and avoids memory allocations.

Write a HashMap as a list of key-value pairs in to particular order, without the length information.

Write a HashSet as a list of keys in no particular order, without the length information.

Write a Map as a list of key-value pairs ordered by the key, without the length information.

Write a BTreeSet as an ascending list of keys, without the length information.

Write a slice of elements, without including length information. This is intended to be used either when the length is statically known, or when the length is serialized independently as part of a bigger structure.

Serialize the given value to a freshly allocated vector of bytes using the provided Serial instance.

Terminate execution immediately without panicking. When the std feature is enabled this is just std::process::abort. When std is not present and the target architecture is wasm32 this will simply emit the unreachable instruction.

Type Definitions

A borrowed attribute value. The slice will have at most 31 bytes. The meaning of the bytes is dependent on the type of the attribute.

Reexport of the HashMap from hashbrown with the default hasher set to the fnv hash function.

Reexport of the HashSet from hashbrown with the default hasher set to the fnv hash function.

Index of the identity provider on the chain. An identity provider with the given index will not be replaced, so this is a stable identifier.

The expected return type of the init method of the smart contract, parametrized by the state type of the smart contract.

An owned counterpart of AttributeValue, more convenient for testing.

A policy with a vector of attributes, fully allocated and owned. This is in contrast to a policy which is lazily read from a read source. The latter is useful for efficiency, this type is more useful for testing since the values are easier to construct.

A type alias used to indicate that the value is a result of parsing from binary via the Serial instance.

The expected return type of the receive method of a smart contract.

Time at the beginning of the current slot, in miliseconds since unix epoch.

Attribute Macros

Sets the cfg for testing targeting either Wasm and native.

Derive the appropriate export for an annotated test function, when feature “wasm-test” is enabled, otherwise behaves like #[test].

Marks a type as the contract state. Currently only used for generating the schema of the contract state. If the feature build-schema is not enabled this has no effect.

Derive the appropriate export for an annotated init function.

Derive the appropriate export for an annotated receive function.

Derive Macros

Derive the Deserial trait. See the documentation of derive(Serial) for details and limitations.

Derive the conversion of enums that represent error types into the Reject struct which can be used as the error type of init and receive functions. Creating custom enums for error types can provide meaningful error messages to the user of the smart contract.

Derive the SchemaType trait for a type. If the feature build-schema is not enabled this is a no-op, i.e., it does not produce any code.

Derive the Serial trait for the type.

A helper macro to derive both the Serial and Deserial traits. [derive(Serialize)] is equivalent to [derive(Serial,Deserial)], see documentation of the latter two for details and options.