Network & Transaction APIs
Each runtime method has access to the current execution context, which provides access to the following APIs: network and transaction. Both of these allow you to tap into information about the current transaction execution, such as the current block height or the transaction sender.
Network API
The network API provides in-runtime method access to the observed network state. Following APIs are available under this.network within
a runtime method:
- Current block height
- Previous block’s state root hash
@runtimeModule()
export class Mintery extends RuntimeModule<Record<string, never>> {
public constructor(@inject("Balances") public balances: Balances) {
super();
}
@runtimeMethod()
public async mint(tokenId: TokenId, address: PublicKey, amount: UInt64) {
const currentBlockHeight = this.network.block.height.value;
assert(
UInt64.Safe.fromField(currentBlockHeight).equals(UInt64.from(0)),
"Minting is only allowed at the genesis block"
);
await this.balances.setBalance(tokenId, address, amount);
}
@runtimeMethod()
public async mintPrivate(proof: MintProof, amount: UInt64) {
assert(
this.network.previous.rootHash.equals(proof.hash),
"Proof is not valid"
);
}
}Transaction API
The transasction API offers access to the information about the transaction which invoked the current runtime method. You can access the following information about the transaction:
- sender
- nonce
- methodId
- argsHash
The methodId and argsHash are used by the runtimeMethod decorator to prove that the runtime method execution was authorized by the transaction sender.
import { runtimeModule, runtimeMethod, RuntimeModule } from "@proto-kit/module";
import { StateMap, assert, state } from "@proto-kit/protocol";
import { Field, PublicKey, Struct } from "o1js";
import { UInt64 } from "@proto-kit/library";
@runtimeModule()
export class GuestBook extends RuntimeModule<Record<string, never>> {
@state() public checkIns = StateMap.from(PublicKey, CheckIn);
@runtimeMethod()
public async checkIn(rating: UInt64) {
assert(rating.lessThanOrEqual(UInt64.from(5)), "Maximum rating can be 5");
const guest = this.transaction.sender.value;
const createdAt = UInt64.Safe.fromField(this.network.block.height.value);
const checkIn = new CheckIn({
guest,
createdAt,
rating,
});
await this.checkIns.set(checkIn.guest, checkIn);
}