Skip to main content

Fuel Usage

When executing WASM code it is sometimes useful to set a limit on how long it can run for. This can be used to prevent potentially malicious or buggy code from running forever and slowing down your application. Wasmbox includes two mechanisms to do this, Epoch Interruption and Fuel Usage.

Fuel usage is easier to use than epochs and provides exact control over the number of instructions that are allowed to run.

tip

Fuel usage is easier to use than epochs but is slower to execute.

Using Fuel

All WASM code is executed within the context of a Store. Add fuel to the Store before executing WASM code.

When the execution runs out of fuel it will cause a "Trap" which is returned to the caller. A trap is either returned as an exception or a result, this can be configured in the code generation settings when importing a WASM asset.

tip

How to get access to the Store depends on which technique you used to load the WASM. For example in the SimpleWasmMonoBehaviour you can just use base.Store

// Add some fuel to the store
store.AddFuel(42);

// Try to run some WASM in this store
try
{
RunSomeWasm(store);
Successul();
}
catch (TrapException ex)
{
// Handle the out-of-fuel exception
if (ex.Type == TrapCode.OutOfFuel)
{
Debug.LogError("Oh no! Ran out of fuel");
}
else
{
Debug.LogError("Oh no! WASM Trap: " + ex.Type);
}
}