pub struct Chain {
    pub accounts: BTreeMap<AccountAddressEq, Account>,
    pub modules: BTreeMap<ModuleReference, ContractModule>,
    pub contracts: BTreeMap<ContractAddress, Contract>,
    /* private fields */
}
Expand description

Represents the blockchain and supports a number of operations, including creating accounts, deploying modules, initializing contract, updating contracts and invoking contracts.

Fields§

§accounts: BTreeMap<AccountAddressEq, Account>

Accounts and info about them. This uses AccountAddressEq to ensure that account aliases are seen as one account.

§modules: BTreeMap<ModuleReference, ContractModule>

Smart contract modules.

§contracts: BTreeMap<ContractAddress, Contract>

Smart contract instances.

Implementations§

source§

impl Chain

source

pub fn builder() -> ChainBuilder

Get a ChainBuilder for constructing a new Chain with a builder pattern.

See the ChainBuilder for more details.

source

pub fn new_with_time_and_rates( block_time: SlotTime, micro_ccd_per_euro: ExchangeRate, euro_per_energy: ExchangeRate ) -> Result<Self, ExchangeRateError>

Create a new Chain where all the configurable parameters are provided.

Returns an error if the exchange rates provided makes one energy cost more than u64::MAX / 100_000_000_000.

For more configuration options and flexibility, use the builder pattern. See Chain::builder.

source

pub fn new_with_time(block_time: SlotTime) -> Self

Create a new Chain with a specified block_time where

  • micro_ccd_per_euro defaults to 50000 / 1
  • euro_per_energy defaults to 1 / 50000.

For more configuration options and flexibility, use the builder pattern. See Chain::builder.

source

pub fn new() -> Self

Create a new Chain where

  • block_time defaults to 0,
  • micro_ccd_per_euro defaults to 50000 / 1
  • euro_per_energy defaults to 1 / 50000.

With these exchange rates, one energy costs one microCCD.

For more configuration options and flexibility, use the builder pattern. See Chain::builder.

source

pub fn calculate_energy_cost(&self, energy: Energy) -> Amount

Helper function for converting Energy to Amount using the two ExchangeRates euro_per_energy and micro_ccd_per_euro.

source

pub fn get_contract(&self, address: ContractAddress) -> Option<&Contract>

Get the state of the contract if it exists in the Chain.

source

pub fn get_module(&self, module: ModuleReference) -> Option<&ContractModule>

Get the the module if it exists in the Chain.

source

pub fn get_account(&self, address: AccountAddress) -> Option<&Account>

Get the state of the account if it exists in the Chain. Account addresses that are aliases will return the same account.

source

pub fn module_deploy_v1( &mut self, signer: Signer, sender: AccountAddress, wasm_module: WasmModule ) -> Result<ModuleDeploySuccess, ModuleDeployError>

Deploy a smart contract module using the same validation rules as enforced by the node.

The WasmModule can be loaded from disk with either module_load_v1 or module_load_v1_raw.

Parameters:

  • signer: the signer with a number of keys, which affects the cost.
  • sender: the sender account.
  • module: the v1 wasm module.
source

pub fn module_deploy_v1_debug( &mut self, signer: Signer, sender: AccountAddress, wasm_module: WasmModule, enable_debug: bool ) -> Result<ModuleDeploySuccess, ModuleDeployError>

Like module_deploy_v1 except that optionally debugging output may be allowed in the module.

source

pub fn contract_init( &mut self, signer: Signer, sender: AccountAddress, energy_reserved: Energy, payload: InitContractPayload ) -> Result<ContractInitSuccess, ContractInitError>

Initialize a contract.

Parameters:

  • signer: the signer with a number of keys, which affects the cost.
  • sender: The account paying for the transaction. Will also become the owner of the contract created.
  • energy_reserved: Amount of energy reserved for executing the init method.
  • payload:
    • amount: The initial balance of the contract. Subtracted from the sender account.
    • mod_ref: The reference to the a module that has already been deployed.
    • init_name: Name of the contract to initialize.
    • param: Parameter provided to the init method.
source

pub fn contract_update( &mut self, signer: Signer, invoker: AccountAddress, sender: Address, energy_reserved: Energy, payload: UpdateContractPayload ) -> Result<ContractInvokeSuccess, ContractInvokeError>

Update a contract by calling one of its entrypoints.

If successful, all changes will be saved.

Parameters:

  • signer: a Signer with a number of keys. The number of keys affects the cost of the transaction.
  • invoker: the account paying for the transaction.
  • sender: the sender of the message, can be an account or contract. For top-level invocations, such as those caused by sending a contract update transaction on the chain, the sender is always the invoker. Here we provide extra freedom for testing invocations where the sender differs.
  • energy_reserved: the maximum energy that can be used in the update.
  • payload: The data detailing which contract and receive method to call etc.
source

pub fn contract_invoke( &self, invoker: AccountAddress, sender: Address, energy_reserved: Energy, payload: UpdateContractPayload ) -> Result<ContractInvokeSuccess, ContractInvokeError>

Invoke a contract by calling an entrypoint.

Similar to Chain::contract_update except that all changes are discarded afterwards. Typically used for “view” functions.

Parameters:

  • invoker: the account used as invoker. Since this isn’t a transaction, it won’t be charged.
  • sender: the sender. Can be either a contract address or an account address.
  • energy_reserved: the maximum energy that can be used in the update.
  • payload: The data detailing which contract and receive method to call etc.
source

pub fn contract_invoke_external( &self, sender: Option<ExternalAddress>, energy_reserved: Energy, payload: InvokeExternalContractPayload, block: Option<BlockHash> ) -> Result<ContractInvokeExternalSuccess, ContractInvokeExternalError>

Invoke an external contract entrypoint.

Similar to Chain::contract_invoke except that it invokes/dry runs a contract on the external node.

Parameters:

  • invoker: the account used as invoker.
    • The account must exist on the connected node.
  • sender: the sender, can also be a contract.
    • The sender must exist on the connected node.
  • energy_reserved: the maximum energy that can be used in the update.
  • payload: The data detailing which contract and receive method to call etc.
  • block: The block in which the invocation will be simulated, as if it was at the end of the block. If None is provided, the external_query_block is used instead.
§Example:
let mut chain = Chain::builder()
                   .external_node_connection(Endpoint::from_static("http://node.testnet.concordium.com:20000"))
                   .build()
                   .unwrap();

// Set up an external contract.
let external_contract =
chain.add_external_contract(ContractAddress::new(1010, 0)).unwrap();

// Set up an external account.
let external_acc =
chain.add_external_account("
3U4sfVSqGG6XK8g6eho2qRYtnHc4MWJBG1dfxdtPGbfHwFxini".parse().unwrap()).
unwrap();

let res = chain.contract_invoke_external(
   Some(ExternalAddress::Account(external_acc)),
   10000.into(),
   InvokeExternalContractPayload {
       amount:       Amount::zero(),
       address:      external_contract,
       receive_name:
OwnedReceiveName::new_unchecked("my_contract.view".to_string()),
       message:      OwnedParameter::empty(),
   },
   None,
);
source

pub fn create_account(&mut self, account: Account) -> Option<Account>

Create an account.

If an account with a matching address already exists this method will replace it and return the old account.

Note that if the first 29-bytes of an account are identical, then they are considered aliases on each other in all methods. See the example below:

let mut chain = Chain::new();
let acc = AccountAddress([
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0,
]);
let acc_alias = AccountAddress([
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
    2, 3, // Only last three bytes differ.
]);

chain.create_account(Account::new(acc, Amount::from_ccd(123)));
assert_eq!(
    chain.account_balance_available(acc_alias), // Using the alias for lookup.
    Some(Amount::from_ccd(123))
);
source

pub fn add_external_account( &mut self, address: AccountAddress ) -> Result<ExternalAccountAddress, ExternalNodeError>

Add an external account from a connected external node.

If the account exists on the external node at the time of the external_query_block, then an ExternalAccountAddress is returned. The address can be used with Chain::contract_invoke_external. Otherwise, an error is returned.

Barring external node errors, the method is idempotent, and so it can be called multiple times with the same effect.

source

pub fn add_external_contract( &mut self, address: ContractAddress ) -> Result<ExternalContractAddress, ExternalNodeError>

Add an external contract from a connected external node.

If the contract exists on the external node at the time of the external_query_block, then an ExternalContractAddress is returned. The address can be used with Chain::contract_invoke_external. Otherwise, an error is returned.

Barring external node errors, the method is idempotent, and so it can be called multiple times with the same effect.

source

pub fn account_balance(&self, address: AccountAddress) -> Option<AccountBalance>

Returns the balance of an account if it exists.

source

pub fn account_balance_available( &self, address: AccountAddress ) -> Option<Amount>

Returns the available balance of an account if it exists.

source

pub fn contract_balance(&self, address: ContractAddress) -> Option<Amount>

Returns the balance of an contract if it exists.

source

pub fn contract_state_lookup( &self, address: ContractAddress, key: &[u8] ) -> Option<Vec<u8>>

Helper method for looking up part of the state of a smart contract, which is a key-value store.

source

pub fn account( &self, address: AccountAddress ) -> Result<&Account, AccountDoesNotExist>

Returns an immutable reference to an Account.

source

pub fn account_exists(&self, address: AccountAddress) -> bool

Check whether an Account exists.

source

pub fn contract_exists(&self, address: ContractAddress) -> bool

Check whether a Contract exists.

source

pub fn set_exchange_rates( &mut self, micro_ccd_per_euro: ExchangeRate, euro_per_energy: ExchangeRate ) -> Result<(), ExchangeRateError>

Try to set the exchange rates on the chain.

Will fail if they result in the cost of one energy being larger than u64::MAX / 100_000_000_000.

source

pub fn tick_block_time( &mut self, duration: Duration ) -> Result<(), BlockTimeOverflow>

Tick the block time on the Chain by a Duration.

Returns an error if ticking causes the block time to overflow.

§Example

// Block time defaults to 0.
let mut chain = Chain::new();

// Increase block time by 123 milliseconds.
chain.tick_block_time(Duration::from_millis(123)).unwrap();

// Block time has now increased.
assert_eq!(chain.block_time(), Timestamp::from_timestamp_millis(123));
source

pub fn micro_ccd_per_euro(&self) -> ExchangeRate

Return the current microCCD per euro exchange rate.

source

pub fn euro_per_energy(&self) -> ExchangeRate

Return the current euro per energy exchange rate.

source

pub fn block_time(&self) -> Timestamp

Return the current block time.

source

pub fn external_query_block( &self ) -> Result<BlockHash, ExternalNodeNotConfigured>

Return the block used for external queries by default.

The block can be set with ChainBuilder::external_query_block when building the Chain.

This method returns an error if the external node has not been configured.

Trait Implementations§

source§

impl Debug for Chain

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Chain

source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl !Freeze for Chain

§

impl !RefUnwindSafe for Chain

§

impl Send for Chain

§

impl Sync for Chain

§

impl Unpin for Chain

§

impl !UnwindSafe for Chain

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> Conv for T

source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
source§

impl<T> FmtForward for T

source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoRequest<T> for T

source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
source§

impl<T> Pipe for T
where T: ?Sized,

source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
source§

impl<T> Pointable for T

source§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> Tap for T

source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
source§

impl<T> TryConv for T

source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more