Skip to main content

fluentbase_runtime/syscall_handler/host/
charge_fuel_manually.rs

1/// Builtin to manually charge and refund fuel when VM metering is disabled.
2///
3/// TODO(dmitry123): Remove this method for the finalized builtin scheme.
4use crate::RuntimeContext;
5use rwasm::{StoreTr, TrapCode, Value};
6
7/// Validates that fuel metering is disabled, applies manual charge/refund, and returns remaining fuel.
8pub fn syscall_charge_fuel_manually_handler(
9    caller: &mut impl StoreTr<RuntimeContext>,
10    params: &[Value],
11    result: &mut [Value],
12) -> Result<(), TrapCode> {
13    let (fuel_consumed, fuel_refunded) =
14        (params[0].i64().unwrap() as u64, params[1].i64().unwrap());
15    caller.try_consume_fuel(fuel_consumed)?;
16    syscall_charge_fuel_manually_impl(caller.data_mut(), fuel_consumed, fuel_refunded)?;
17    let remaining_fuel = caller.remaining_fuel().unwrap_or(u64::MAX);
18    result[0] = Value::I64(remaining_fuel as i64);
19    Ok(())
20}
21
22/// Updates context fuel accounting with manual consumption and refund values.
23pub fn syscall_charge_fuel_manually_impl(
24    ctx: &mut RuntimeContext,
25    fuel_consumed: u64,
26    fuel_refunded: i64,
27) -> Result<u64, TrapCode> {
28    let new_fuel_consumed = ctx
29        .execution_result
30        .fuel_consumed
31        .saturating_add(fuel_consumed);
32    if new_fuel_consumed > ctx.fuel_limit {
33        return Err(TrapCode::OutOfFuel);
34    }
35    ctx.execution_result.fuel_consumed = new_fuel_consumed;
36    ctx.execution_result.fuel_refunded += fuel_refunded;
37    Ok(0)
38}