Skip to content

Host functions

A module can import only these functions. Every SDK wraps them; the raw ABI is listed for reference. The table below is the interface live today (execution revision 2). Execution revision 3 adds caller identity, time, context metadata, native cryptography and indexed events once the network activates it.

Host import What it does Rust Go AssemblyScript JS engine Python
storage.get Read a key of this module’s state storage::get, get_string, get_json StorageGet, StorageGetString, StorageGetJSON storage.get(key) ("" if unset) storage.get, db.get(key, default) hive.storage.get, hive.db.get(key, default)
storage.set Write a key (an empty value deletes it) storage::set, set_json StorageSet, StorageSetString, StorageSetJSON storage.set(key, value) storage.set, db.set hive.storage.set, hive.db.set
storage.del Delete a key storage::del StorageDel storage.del storage.del / db.del hive.storage.delete / hive.db.delete
hive.emit Record an event {name, data} emit(name, &data) Emit, EmitRaw hive.emit(name, dataJson) hive.emit(name, data) hive.emit(name, data)
hive.call Call another deployed module synchronously call, call_json Call, CallJSON hive.call, hive.tryCall, hive.tryCallRaw hive.call, hive.callRaw, hive.tryCall hive.call, hive.call_raw, hive.try_call
crypto.hash Keccak-256 of bytes, as 0x + 64 hex hash(&[u8]) Hash(data) hive.hash(data) hive.hash(data) hive.hash(data)
console.log Debug log on the node (no consensus effect) log(&str) Log, Logf hive.log(msg) hive.log(…), console.log(…), ctx.log.info(…) hive.log(…), ctx.log.info(…)
hive.abort Fail the call with a message abort(&str), or return Err Abort(msg), or return an error hive.fail(msg) hive.fail(msg) or throw hive.fail(msg) or raise
  • State is a key/value map private to the module (namespaced by its address). A module can never read or write another module’s keys; use hive.call to ask the other module.
  • Keys are 1–256 bytes, values up to 64 KiB, at most 1 MiB written per top-level call.
  • Writes are buffered and committed only if the whole top-level call succeeds. A failed call (error, abort, trap, out of gas) writes nothing and emits nothing.
  • Storage exists only for modules run through validator rounds (/v1/execute). Committee workers are stateless. Two ways to run a module
  • Name: [A-Za-z0-9_.:-]{1,64}. Data: JSON that canonical JSON accepts: no floats, integers within ±(2^53−1). Use integer minor units (cents, micro-units) or strings.
  • Up to 64 events per call, 16 KiB of data each. Events are part of the receipt (events_hash).
  • Function outputs are plain UTF-8 text and may contain any JSON, floats included; only events and signed structures are restricted.
  • The callee runs in a fresh instance with all remaining gas; what it uses is charged to the caller.
  • Callee success: its state writes and events merge into the caller’s call. Callee failure: they are discarded and the caller gets an error code it can handle.
  • Depth limit 8. The call is synchronous and atomic with the caller.
Code Meaning
-1 Module not found
-2 Function not found
-3 Callee failed (trap, abort, error)
-4 Reserved: out of gas always fails the whole call
-5 Call depth exceeded
-6 Malformed address

Example of cross-language calls: Cross-module composition.

The input is a byte string, usually JSON. Through the API, a string input is passed byte for byte and any other JSON value is passed as canonical JSON (floats are rejected; send them inside a string). Outputs must be valid UTF-8 and at most 1 MiB.

Revision 3 only adds imports; the guest ABI name stays hive-wasm-v1, and existing artifacts and module addresses do not change. The HiveKit compilers emit a revision 3 import only when your code uses it, so a module that does not use the new functions stays valid under revision 2 and keeps its address.

Conventions for every new import:

  • Pointers and lengths are unsigned 32-bit; an out-of-bounds range traps.
  • Fixed-size outputs (hashes, addresses, ids) are written to a guest buffer at out_ptr. The host never calls back into the module for them.
  • String outputs use the packed (ptr, len) return, like storage.get; 0 is the empty string. They count against the host re-entry limit (16).
  • Each function charges its full gas cost before doing any work. Not enough gas is out of gas.
  • Invalid crypto inputs (bad signature, bad key) are return codes, never traps.
Host import Signature Returns Rust Go AssemblyScript JS engine Python
ctx.caller () -> i64 packed principal of the immediate caller; 0 if anonymous ctx::caller() -> Principal Caller() Principal hive.caller() ctx.caller, hive.caller() ctx.caller
ctx.origin () -> i64 packed principal of the top-level signer; 0 if unsigned ctx::origin() Origin() hive.origin() ctx.origin, hive.origin() ctx.origin
ctx.time () -> i64 context time, unix seconds ctx::time(), ctx::monotonic_time() Now(), MonotonicNow() hive.now(), hive.monotonicNow() ctx.time, hive.time() ctx.time, hive.monotonic_time()
ctx.kind () -> i32 0 direct call, 1 exec: round, 2 committee task ctx::kind() Kind() hive.kind() ctx.kind ctx.kind
ctx.module_address () -> i64 packed 66-byte address of the module running this frame ctx::module_address() Self() hive.self() ctx.self ctx.module
ctx.round_id () -> i64 packed round id; 0 for direct calls ctx::round_id() RoundID() hive.roundId() ctx.roundId ctx.round_id
ctx.call_id (out_ptr) -> i32 1 and the 32-byte call_hash written; 0 for unsigned calls ctx::call_id() -> Option<[u8; 32]> CallID() hive.callId() ctx.callId ctx.call_id
ctx.network () -> i64 packed network_id (testnet: necter-testnet) ctx::network() Network() hive.network() ctx.network ctx.network
ctx.gas_left () -> i64 gas remaining after this call’s own charge ctx::gas_left() GasLeft() hive.gasLeft() hive.gasLeft() hive.gas_left()
crypto.verify_ed25519 (pk_ptr, msg_ptr, msg_len, sig_ptr) -> i32 1 valid, 0 invalid crypto::verify_ed25519 VerifyEd25519 hive.crypto.verifyEd25519 hive.crypto.verifyEd25519 hive.crypto.verify_ed25519
crypto.ecrecover_secp256k1 (hash_ptr, sig_ptr, out_ptr) -> i32 0 ok (20-byte address written), 1 invalid (nothing written) crypto::ecrecover Ecrecover hive.crypto.ecrecover hive.crypto.ecrecover hive.crypto.ecrecover
crypto.keccak256 (ptr, len, out_ptr) writes 32 raw bytes crypto::keccak256 Keccak256 hive.crypto.keccak256 hive.crypto.keccak256 hive.crypto.keccak256
crypto.sha256 (ptr, len, out_ptr) writes 32 raw bytes crypto::sha256 Sha256 hive.crypto.sha256 hive.crypto.sha256 hive.crypto.sha256
hive.emit_indexed (name_ptr, name_len, topics_ptr, topics_len, data_ptr, data_len) records an event with 0–4 topics emit_indexed(name, &topics, &data) EmitIndexed(name, topics, data) hive.emitIndexed(name, topics, json) ctx.emit(name, data, { topics }) hive.emit(name, data, topics=[…])

The SDKs also add helpers that are not host imports: a Principal type (parse, print, compare, topic()), an EIP-191 hash (crypto::eip191_hash, EIP191Hash, hive.crypto.eip191Hash, hive.crypto.eip191_hash) built from crypto.keccak256, and setters for caller, origin, time, kind and round id in each local test runner, so module tests run without a node. Gas costs: Gas and limits.

ctx.caller and ctx.origin return a principal, an ASCII string in one of four forms:

Form Length Meaning
"" 0 anonymous (unsigned call)
0x + 40 lowercase hex 42 secp256k1 account (an EVM address), scheme eip191
ed25519: + 64 lowercase hex 72 ed25519 public key, scheme ed25519
0x + 64 lowercase hex 66 module address (only as the caller inside hive.call)

The forms differ in length and prefix, so a module can never confuse a module with a user. Every principal the host returns is already canonical: compare with plain string equality.

  • At the top level, caller = origin = the signer of the call (or both empty for an unsigned call).
  • In a frame entered by hive.call from module A, caller is A’s module address and origin is unchanged. A module calling itself sees its own address as caller.
ownable_counter.rs (excerpt)
use hivekit::prelude::*;
fn require_owner() -> Result<Principal, String> {
let owner: Principal = storage::get_string("owner")
.and_then(|s| s.parse().ok())
.ok_or("not initialised")?;
if ctx::caller() != owner {
return Err("only the owner".into());
}
Ok(owner)
}
/// The first signed caller becomes the owner.
#[hive_export]
fn init() -> Result<Value, String> {
let caller = ctx::caller();
if caller.is_anonymous() {
return Err("init must be a signed call".into());
}
storage::set("owner", caller.to_string());
emit_indexed("owner_set", &[caller.topic()], &json!({ "owner": caller }));
Ok(json!({ "owner": caller }))
}

The caller is set by the network from a signed call; the module never parses a signature itself. Failure modes: none besides gas and the re-entry limit.

ctx.time() is the context time of the execution:

Execution Value
Validator round (exec:) the round’s issued_at, chosen by the Hub; every validator rejects the round if it is more than 300 s from its own clock
Committee task (task:) the task’s issued_at
Direct call to one node (no round) that node’s clock; not agreed by anyone, for development only

Guaranteed: constant within one execution in every frame, identical on every validator of a round, and within 300 s of every honest voting validator’s clock.

Not guaranteed: monotonic (a later round can be up to 600 s “earlier”), unique (many rounds share a second), or related to Ethereum block time. Whoever issues the round can choose the time within ±300 s; assume a caller can too. monotonic_time() / MonotonicNow() returns max(ctx.time(), stored) and stores the high-water mark (it writes state).

  • Safe: expiries and deadlines with at least 10 minutes of slack, auction close with a soft-close extension, hourly or daily buckets for rate limits and metering, approximate timestamps, vesting and cool-downs measured in hours or days.
  • Unsafe: ordering events by time (use a counter), decisions inside the last 5 minutes of a deadline, per-second interest, randomness, comparing times across modules.

The envelope’s own issued_at is chosen by the signer and only bounds the call’s validity; it is never the module’s time. Failure modes: none.

  • ctx.module_address saves compiling the module’s own address in (impossible anyway: the address covers the code).
  • ctx.call_id is the signed call’s call_hash. It is stable across retries of the same signed call (a new round has a new round_id but the same call_hash), so it is the right idempotency key.
  • ctx.round_id is unique per round and includes the Hub’s nonce. Never use it as randomness.
  • ctx.gas_left lets a batch loop stop before running out of gas. It returns the same value on every engine.

Failure modes: none.

pk is 32 bytes; sig is 64 bytes (ed25519) or 65 bytes r ‖ s ‖ v (secp256k1); hash is 32 bytes. msg_len and len are capped at 1 MiB; a longer length traps before any charge.

  • ed25519 uses strict verification: a key that does not decompress, a non-canonical S, or a small-order A or R returns 0. The rule is pinned by the RFC 8032 vectors and the “Taming the many EdDSAs” edge cases.
  • secp256k1 recovery accepts v ∈ {27, 28} or {0, 1}, requires r and s in 1..n−1 and low s (EIP-2), and rejects recovery ids with the x-overflow bit. Ethereum’s ecrecover precompile accepts high s; this function does not, so every signature has exactly one accepted encoding. Wallets produce low s. The output is keccak256(uncompressed public key)[12..32]. hash is used as is: build EIP-191 digests with crypto.keccak256 (the SDKs’ eip191_hash helpers do).
  • crypto.keccak256 and crypto.sha256 write raw 32-byte digests. The existing crypto.hash still returns Keccak-256 as a 66-byte hex string; it is repriced under revision 3.
use hivekit::prelude::*;
// Verify a backend attestation over `msg` with a known ed25519 key.
fn attested(pk: &[u8; 32], msg: &[u8], sig: &[u8; 64]) -> bool {
crypto::verify_ed25519(pk, msg, sig)
}
// Recover the EVM address that personal_sign'ed `msg`.
fn signer_of(msg: &[u8], sig: &[u8; 65]) -> Option<[u8; 20]> {
crypto::ecrecover(&crypto::eip191_hash(msg), sig)
}

These replace signature checks written in module code: ed25519 drops from about 2.5 M gas to 235,000 and secp256k1 recovery from about 9.6 M to 780,000. For checking who called you, prefer a signed call and ctx.caller(): the network verifies the signature before your code runs. Failure modes: out-of-bounds pointers and over-long lengths trap; everything else is a return code.

hive.emit_indexed records an event with up to four 32-byte topics that the Hub indexes, so apps can query “all orders of this buyer” without parsing every event. topics_len must be a multiple of 32 and at most 128; otherwise it traps. Name and data rules, and the 64-events-per-call limit, are shared with hive.emit. Details and the query API: Events and indexing.

A receipt gains a context_hash (receipt v: 2) when the call was signed, or when any frame called ctx.caller, ctx.origin, ctx.time, ctx.kind, ctx.round_id, ctx.call_id or ctx.network, even if the execution then failed. ctx.module_address, ctx.gas_left, the crypto functions and hive.emit_indexed do not add a context (topics are covered by events_hash). Every other execution keeps its v1 receipt byte for byte. Receipts

Under revision 3, storage.set and storage.del trap on any key starting with the five bytes 0xFF "ndsr": the runtime keeps signed-call nonces there. storage.get may read them.

Feature Status
ctx.random (randomness for committee tasks) planned Deferred. Importing it is rejected at load as an unknown import.
ctx.beacon(epoch) (delayed public randomness from a past beacon) planned Deferred, same treatment.
eip712 signed calls (typed data) planned Deferred. The scheme name is reserved and refused.

Until then, use commit-reveal or a seed in the input for draws: Determinism rules.