Host Communication
One of the things that your contract will probably do is to query the host for some information - what is the current time? Who called me? Following example shows how to do this:
use odra::prelude::*;
#[odra::module]
pub struct HostContract {
name: Var<String>,
created_at: Var<u64>,
created_by: Var<Address>
}
#[odra::module]
impl HostContract {
pub fn init(&mut self, name: String) {
self.name.set(name);
self.created_at.set(self.env().get_block_time());
self.created_by.set(self.env().caller())
}
pub fn name(&self) -> String {
self.name.get_or_default()
}
pub fn created_at(&self) -> u64 {
self.created_at.get().unwrap()
}
pub fn created_by(&self) -> Address {
self.created_by.get().unwrap()
}
}
The two new getters use get().unwrap() rather than the get_or_default() used for name.
get_or_default() requires the stored type to implement Default, and Address does not - so for a
Var<Address> you must use get() (and deal with the Option) or get_or_revert_with(...).
As you can see, we are using self.env(). It is an implementation of Module::env(), autogenerated
by #[odra::module] attribute. The function returns a reference to the ContractEnv (you can read more in
the Backend section). This is a structure that provides access to the host functions and variables.
In this example, we use two of them:
get_block_time()- returns the current block time as u64.caller()- returns an OdraAddressof the caller (this can be an external caller or another contract).
You will learn more functions that Odra exposes from host and types it uses in further articles.
What's next
In the next article, we'll dive into testing your contracts with Odra, so you can check that the code we presented in fact works!