Attribute Macro pbc_contract_codegen::zk_on_variable_inputted
source · #[zk_on_variable_inputted]
Expand description
Secret variable input zero-knowledge contract annotation
OPTIONAL HOOK: This is an optional hook, and is not required for a well-formed zero-knowledge contract. The default behaviour is to do nothing.
If the annotated function panics changes to the contract state will be rolled back.
Annotated function is automatically called when a Zk variable is confirmed and fully inputted. This hook is exclusively called by the blockchain itself, and cannot be called manually from the dashboard, nor from another contract.
Allows the contract to automatically react to ZK inputs.
Must have a signature of the following format:
#[zk_on_variable_inputted(shortname = 0x13)]
pub fn zk_on_variable_inputted(
context: ContractContext,
state: ContractState,
zk_state: ZkState<Metadata>,
variable_id: SecretVarId,
) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>)
with following constraints:
ContractState
must be the type annotated withstate
, and must have anpbc_traits::ReadWriteState
implementation.- The
Metadata
type given toZkState
andZkInputDef
must be identical both for individual functions, and across the entire contract. - This function is only available with the
zk
feature enabled.
The function receives:
ContractState
: The previous states.ZkState<Metadata>
: The current state of the zk computation.ContractContext
: The current contract context.SecretVarId
: Id of the variable.
The function must return a tuple containing:
- New public state.
- Vector of
EventGroup
; a list of interactions with other contracts. Vec<ZkStateChange>
declaring how to change the zk contract state.
§Example
This hook is commonly used to start the computation when enough inputs have been given, as demonstrated in the following example:
type ContractState = u32;
type Metadata = u32;
const SHORTNAME_MY_COMPUTATION : ShortnameZkComputation = ShortnameZkComputation::from_u32(0x11);
#[zk_on_variable_inputted(shortname=0x13)]
pub fn zk_on_variable_inputted(
context: ContractContext,
state: ContractState,
zk_state: ZkState<Metadata>,
variable_id: SecretVarId,
) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>) {
let zk_state_changes = if (zk_state.secret_variables.len() > 5) {
vec![ZkStateChange::start_computation(SHORTNAME_MY_COMPUTATION, vec![1, 2, 3], Some(SHORTNAME_MY_ON_COMPUTE_COMPLETE))]
} else {
vec![]
};
(state, vec![], zk_state_changes)
}
#[zk_on_compute_complete(shortname = 0x13)]
pub fn my_on_compute_complete(
context: ContractContext,
state: ContractState,
zk_state: ZkState<Metadata>,
created_variables: Vec<SecretVarId>,
) -> (ContractState, Vec<EventGroup>, Vec<ZkStateChange>) {
// ...
}