[][src]Crate concordium_std

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 methodss
  • 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.

Modules

attributes

Currently defined attributes possible in a policy.

collections

Re-export.

convert

Re-export.

marker

Primitive traits and types representing basic properties of types.

mem

Re-export.

schema

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.

test_infrastructure

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

Macros

bail

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.

claim

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.

claim_eq

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

claim_ne

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

ensure

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.

ensure_eq

Variants of ensure for ease of use in certain contexts.

ensure_ne

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

fail

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

AccountAddress

Address of an account, as raw bytes.

Action

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.

Amount

The type of amounts on the chain

AttributeTag

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

AttributesCursor

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

ChainMetadata

Chain metadata accessible to both receive and init methods.

ContractAddress

Address of a contract.

ContractState

A type representing the constract state bytes.

Cursor

Add offset tracking inside a data structure.

Duration

Duration of time in milliseconds.

Logger

A type representing the logger.

Parameter

A type representing the parameter to init and receive methods.

ParseError

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

PoliciesIterator

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

Policy on the credential of the account.

Reject

A non-descript error message, signalling rejection of a smart contract invocation.

String

A UTF-8–encoded, growable string.

Timestamp

Timestamp represented as milliseconds since unix epoch.

Vec

A contiguous growable array type, written Vec<T> but pronounced 'vector'.

Enums

Address

Either an address of an account, or contract.

AmountParseError

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.

ParseDurationError
SeekFrom

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

Constants

ACCOUNT_ADDRESS_SIZE

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

Traits

Deserial

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

ExpectErrReport

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

ExpectNoneReport

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

ExpectReport

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

Get

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,

HasActions

An object that can serve to construct actions.

HasChainMetadata

Objects which can access chain metadata.

HasCommonData

Common data accessible to both init and receive methods.

HasContractState

A type that can serve as the contract state type.

HasInitContext

Types which can act as init contexts.

HasLogger

Objects which can serve as loggers.

HasParameter

Objects which can access parameters to contracts.

HasPolicy

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.

HasReceiveContext

Types which can act as receive contexts.

Read

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

Seek

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.

Serial

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

Serialize

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

UnwrapAbort

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

Write

The Write trait provides functionality for writing to byte streams.

Functions

deserial_map_no_length

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.

deserial_map_no_length_no_order_check

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

deserial_set_no_length

Read a BTreeSet as an 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.

deserial_set_no_length_no_order_check

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.

deserial_vector_no_length

Read a vector given a length.

from_bytes

Dual to to_bytes.

serial_map_no_length

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

serial_set_no_length

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

serial_vector_no_length

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.

to_bytes

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

trap

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

AttributeValue

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.

BlockHeight

Height of the block. Height of the genesis block is 0, and otherwise it is always the case that a block has height one more than its parent.

FinalizedHeight

Finalized height. In the context of chain metadata this is the height of the block which is explicitly recorded as the last finalized block in the block under consideration.

IdentityProvider

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.

InitResult

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

OwnedAttributeValue

An owned counterpart of AttributeValue, more convenient for testing.

OwnedPolicy

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.

ParseResult

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

ReceiveResult

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

SlotNumber

Genesis block has slot number 0, and otherwise it is always the case that a parent of a block has a slot number strictly less than the block itself. However in contrast to BlockHeight, slot numbers are not strictly sequential, there will be gaps.

SlotTime

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

Attribute Macros

concordium_cfg_test

Sets the cfg for testing targeting either Wasm and native.

concordium_test

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

contract_state

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.

init

Derive the appropriate export for an annotated init function.

receive

Derive the appropriate export for an annotated receive function.

Derive Macros

Deserial

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

SchemaType

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.

Serial

Derive the Serial trait for the type.

Serialize

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.