Skip to main content

fluentbase_runtime/syscall_handler/host/
charge_fuel.rs

1/// Builtin that charges fuel against the VM and the runtime accounting.
2use crate::RuntimeContext;
3use rwasm::{StoreTr, TrapCode, Value};
4
5/// Consumes fuel from the engine and mirrors the consumption in the runtime context.
6pub fn syscall_charge_fuel_handler(
7    caller: &mut impl StoreTr<RuntimeContext>,
8    params: &[Value],
9    _result: &mut [Value],
10) -> Result<(), TrapCode> {
11    let fuel_consumed = params[0].i64().unwrap() as u64;
12    // Charge the engine fuel counter (instructions + builtins).
13    caller.try_consume_fuel(fuel_consumed)?;
14    // Mirror the charge in the runtime context (builtins-managed accounting).
15    syscall_charge_fuel_impl(caller.data_mut(), fuel_consumed)?;
16    Ok(())
17}
18
19/// Adds the consumed fuel to the runtime context and checks against the context fuel limit.
20pub fn syscall_charge_fuel_impl(
21    ctx: &mut RuntimeContext,
22    fuel_consumed: u64,
23) -> Result<(), TrapCode> {
24    let new_fuel_consumed = ctx
25        .execution_result
26        .fuel_consumed
27        .saturating_add(fuel_consumed);
28    if new_fuel_consumed > ctx.fuel_limit {
29        return Err(TrapCode::OutOfFuel);
30    }
31    ctx.execution_result.fuel_consumed = new_fuel_consumed;
32    Ok(())
33}