Git Source Inherits: FacetCommonImports Author: @mpetersoCode55, @ShaneDuncan602, @TJ-Everett, @VoR0220 This contract is a critical component of the Rules Engine, enabling secure and flexible rule evaluation and effect execution. This contract serves as the core processor for evaluating rules and executing effects in the Rules Engine. It provides functionality for evaluating policies, rules, and conditions, as well as executing effects based on rule outcomes. The contract also supports foreign calls, dynamic argument handling, and tracker updates.

State Variables

GLOBAL_NONE

uint8 constant GLOBAL_NONE = 0;

GLOBAL_MSG_SENDER

uint8 constant GLOBAL_MSG_SENDER = 1;

GLOBAL_BLOCK_TIMESTAMP

uint8 constant GLOBAL_BLOCK_TIMESTAMP = 2;

GLOBAL_MSG_DATA

uint8 constant GLOBAL_MSG_DATA = 3;

GLOBAL_BLOCK_NUMBER

uint8 constant GLOBAL_BLOCK_NUMBER = 4;

GLOBAL_TX_ORIGIN

uint8 constant GLOBAL_TX_ORIGIN = 5;

Functions

checkPolicies

Evaluates the conditions associated with all applicable rules and returns the result. Primary entry point for policy checks.
function checkPolicies(bytes calldata arguments) public;
Parameters
NameTypeDescription
argumentsbytesFunction arguments, including the function signature and the arguments to be passed to the function.

evaluateForeignCalls

Evaluates foreign calls within the rules engine processor. This function processes and evaluates calls to external contracts or systems as part of the rules engine’s logic. Ensure that the necessary validations and security checks are in place when interacting with foreign calls.
function evaluateForeignCalls(
    uint256 policyId,
    bytes calldata callingFunctionArgs,
    uint256 foreignCallIndex,
    bytes[] memory retVals,
    ForeignCallEncodedIndex[] memory metadata
) internal returns (ForeignCallReturnValue memory retVal);
Parameters
NameTypeDescription
policyIduint256Id of the policy.
callingFunctionArgsbytesrepresentation of the calling function arguments
foreignCallIndexuint256Index of the foreign call.
retValsbytes[]array of return values from previous foreign calls, trackers, etc.
metadataForeignCallEncodedIndex[]
Returns
NameTypeDescription
retValForeignCallReturnValueThe output of the foreign call.

evaluateForeignCallForRule

encodes the arguments and places a foreign call, returning the calls return value as long as it is successful
function evaluateForeignCallForRule(
    ForeignCall memory fc,
    bytes calldata functionArguments,
    bytes[] memory retVals,
    ForeignCallEncodedIndex[] memory metadata,
    uint256 policyId
) internal returns (ForeignCallReturnValue memory retVal);
Parameters
NameTypeDescription
fcForeignCallthe Foreign Call structure
functionArgumentsbytesthe arguments of the rules calling function (to be passed to the foreign call as needed)
retValsbytes[]
metadataForeignCallEncodedIndex[]
policyIduint256
Returns
NameTypeDescription
retValForeignCallReturnValuethe foreign calls return value

evaluateForeignCallForRuleMappedTrackerKey

function evaluateForeignCallForRuleMappedTrackerKey(
    bytes calldata functionArguments,
    bytes[] memory retVals,
    uint256 policyId,
    uint256 trackerIndex,
    bytes memory encodedCall,
    uint256 lengthToAppend,
    bytes memory dynamicData,
    ForeignCallEncodedIndex memory mappedTrackerKeyEI,
    uint256 parameterTypesLength
) internal view returns (bytes memory, uint256, bytes memory);

_foreignCallGetMappedTrackerValue

function _foreignCallGetMappedTrackerValue(
    bytes calldata functionArguments,
    bytes[] memory retVals,
    uint256 policyId,
    uint256 trackerIndex,
    ForeignCallEncodedIndex memory mappedTrackerKeyEI,
    ParamTypes typ
) internal view returns (bytes memory mappedTrackerValue, ParamTypes valueType);

evaluateForeignCallForRuleEncodedValues

Processes encoded values from function arguments for foreign call encoding
function evaluateForeignCallForRuleEncodedValues(
    ForeignCall memory fc,
    ParamTypes argType,
    bytes calldata functionArguments,
    bytes memory encodedCall,
    uint256 lengthToAppend,
    bytes memory dynamicData,
    uint256 i
) internal pure returns (bytes memory, uint256, bytes memory);
Parameters
NameTypeDescription
fcForeignCallThe ForeignCall struct containing call configuration
argTypeParamTypesThe parameter type for the current argument
functionArgumentsbytesThe encoded arguments from the calling function
encodedCallbytesCurrent encoded call data being built
lengthToAppenduint256Current length of dynamic data to append
dynamicDatabytesCurrent dynamic data portion of the call
iuint256Current parameter index being processed
Returns
NameTypeDescription
<none>bytesencodedCall Updated encoded call data
<none>uint256lengthToAppend Updated length of dynamic data
<none>bytesdynamicData Updated dynamic data portion

evaluateForeignCallForRulePlaceholderValues

Processes placeholder values for foreign call encoding
function evaluateForeignCallForRulePlaceholderValues(
    ForeignCall memory fc,
    bytes[] memory retVals,
    ForeignCallEncodedIndex[] memory metadata,
    bytes memory encodedCall,
    uint256 lengthToAppend,
    uint256 i,
    bytes memory dynamicData
) internal view returns (bytes memory, uint256, bytes memory);
Parameters
NameTypeDescription
fcForeignCallThe ForeignCall struct containing call configuration
retValsbytes[]Array of return values from previous operations
metadataForeignCallEncodedIndex[]Array of encoded index metadata for parameter resolution
encodedCallbytesCurrent encoded call data being built
lengthToAppenduint256Current length of dynamic data to append
iuint256Current parameter index being processed
dynamicDatabytesCurrent dynamic data portion of the call
Returns
NameTypeDescription
<none>bytesencodedCall Updated encoded call data
<none>uint256lengthToAppend Updated length of dynamic data
<none>bytesdynamicData Updated dynamic data portion

concatenateCallOnMemory

function concatenateCallOnMemory(
    bytes memory encodedCall,
    uint256 lengthToAppend,
    bytes memory dynamicData,
    bytes memory value,
    ParamTypes argType,
    uint256 parameterTypesLength
) internal pure returns (bytes memory, uint256, bytes memory);

_handleGlobalVarForForeignCall

Handles global variable processing for foreign call encoding Internal function that processes global variable types and encodes them appropriately for foreign call arguments
function _handleGlobalVarForForeignCall(
    ForeignCall memory fc,
    ParamTypes argType,
    uint8 globalVarType,
    bytes memory encodedCall,
    uint256 lengthToAppend,
    bytes memory dynamicData
) private view returns (bytes memory, uint256, bytes memory);
Parameters
NameTypeDescription
fcForeignCallThe ForeignCall struct containing the call configuration and parameter types
argTypeParamTypesThe expected parameter type for the global variable in the foreign call
globalVarTypeuint8An uint8 identifier representing which global variable to process:
encodedCallbytesThe current encoded call data being built for the foreign call
lengthToAppenduint256The current length of dynamic data to be appended
dynamicDatabytesThe current dynamic data portion of the encoded call
Returns
NameTypeDescription
<none>bytesencodedCall The updated encoded call data with the global variable parameter added
<none>uint256lengthToAppend The updated length of dynamic data after processing
<none>bytesdynamicData The updated dynamic data portion after processing

_checkPolicy

Checks a specific policy for compliance.
function _checkPolicy(uint256 _policyId, bytes calldata _arguments) internal returns (bool retVal);
Parameters
NameTypeDescription
_policyIduint256The ID of the policy to check.
_argumentsbytesFunction arguments for the policy evaluation.
Returns
NameTypeDescription
retValboolTrue if the policy passes, false otherwise.

_evaluateRulesAndExecuteEffects

Evaluates rules and executes their effects based on the evaluation results.
function _evaluateRulesAndExecuteEffects(
    mapping(uint256 ruleId => RuleStorageSet) storage _ruleData,
    uint256 _policyId,
    uint256[] memory _applicableRules,
    bytes calldata _callingFunctionArgs
) internal returns (bool _retVal);
Parameters
NameTypeDescription
_ruleDatamapping(uint256 ruleId => RuleStorageSet)The mapping of rule IDs to rule storage sets.
_policyIduint256The ID of the policy being evaluated.
_applicableRulesuint256[]An array of applicable rule IDs.
_callingFunctionArgsbytesThe arguments for the calling function.
Returns
NameTypeDescription
_retValboolTrue if all rules pass, false otherwise.

_evaluateIndividualRule

evaluates an individual rules condition(s)
function _evaluateIndividualRule(
    Rule storage _rule,
    uint256 _policyId,
    bytes calldata _callingFunctionArgs,
    PlaceholderType _kind
) internal returns (bool response);
Parameters
NameTypeDescription
_ruleRulethe rule structure containing the instruction set, with placeholders, to execute
_policyIduint256Policy id being evaluated.
_callingFunctionArgsbytesthe values to replace the placeholders in the instruction set with.
_kindPlaceholderTypethe type of placeholders to build
Returns
NameTypeDescription
responseboolthe result of the rule condition evaluation

_buildArguments

Constructs the arguments required for building the rule’s place holders.
function _buildArguments(
    Rule storage _rule,
    uint256 _policyId,
    bytes calldata _callingFunctionArgs,
    PlaceholderType _kind
) internal returns (bytes[] memory, Placeholder[] memory);
Parameters
NameTypeDescription
_ruleRuleThe storage reference to the Rule struct containing the rule’s details.
_policyIduint256The unique identifier of the policy associated with the rule.
_callingFunctionArgsbytesThe calldata containing the arguments for the calling function.
_kindPlaceholderTypethe type of placeholders to build
Returns
NameTypeDescription
<none>bytes[]A tuple containing: - An array of bytes representing the constructed arguments. - An array of Placeholder structs used for argument substitution.
<none>Placeholder[]

_run

Internal function to decode the arguments and do the comparisons.
function _run(uint256[] memory _prog, Placeholder[] memory _placeHolders, uint256 _policyId, bytes[] memory _arguments)
    internal
    returns (bool);
Parameters
NameTypeDescription
_proguint256[]An array of uint256 representing the program to be executed.
_placeHoldersPlaceholder[]An array of Placeholder structs used within the program.
_policyIduint256The ID of the policy associated with the program execution.
_argumentsbytes[]An array of bytes containing additional arguments for the program.
Returns
NameTypeDescription
<none>boolA boolean indicating the result of the program execution.

_updateTrackerValue

This function updates the tracker value with the information provided
function _updateTrackerValue(uint256 _policyId, uint256 _trackerId, uint256 _trackerValue) internal;
Parameters
NameTypeDescription
_policyIduint256Policy id being evaluated.
_trackerIduint256ID of the tracker to update.
_trackerValueuint256Value to update within the tracker

_updateTrackerValue

Internal function to update the value of a tracker associated with a specific policy.
function _updateTrackerValue(uint256 _policyId, uint256 _trackerId, bytes memory _trackerValue, bool _mightNeedHashing)
    internal;
Parameters
NameTypeDescription
_policyIduint256The ID of the policy to which the tracker belongs.
_trackerIduint256The ID of the tracker whose value is being updated.
_trackerValuebytesThe new value to be assigned to the tracker, encoded as bytes.
_mightNeedHashingbool

_updateMappedTrackerValue

This function updates the tracker value with the information provided for a mapped tracker
function _updateMappedTrackerValue(
    uint256 _policyId,
    uint256 _trackerId,
    uint256 _trackerValue,
    uint256 _mappedTrackerKey
) internal;
Parameters
NameTypeDescription
_policyIduint256Policy id being evaluated.
_trackerIduint256ID of the tracker to update.
_trackerValueuint256Value to update within the tracker
_mappedTrackerKeyuint256

_getMappedTrackerValue

function _getMappedTrackerValue(uint256 _policyId, uint256 _trackerId, uint256 _mappedTrackerKey)
    internal
    view
    returns (bytes memory, ParamTypes);

_updateMappedTrackerValue

Internal function to update the value of a mapped tracker associated with a specific policy.
function _updateMappedTrackerValue(
    uint256 _policyId,
    uint256 _trackerId,
    bytes memory _trackerValue,
    uint256 _mappedTrackerKey,
    bool _mightNeedHashing
) internal;
Parameters
NameTypeDescription
_policyIduint256The ID of the policy to which the tracker belongs.
_trackerIduint256The ID of the tracker whose value is being updated.
_trackerValuebytesThe new value to be assigned to the tracker, encoded as bytes.
_mappedTrackerKeyuint256
_mightNeedHashingbool

_loadApplicableRules

Loads applicable rules for a given calling function.
function _loadApplicableRules(
    mapping(uint256 ruleId => RuleStorageSet) storage _ruleData,
    Policy storage _policy,
    bytes4 _callingFunction
) internal view returns (uint256[] memory);
Parameters
NameTypeDescription
_ruleDatamapping(uint256 ruleId => RuleStorageSet)The mapping of rule IDs to rule storage sets.
_policyPolicyThe policy structure containing the rules.
_callingFunctionbytes4The function signature to match rules against.
Returns
NameTypeDescription
<none>uint256[]An array of applicable rule IDs.

_handleForeignCall

Processes foreign calls within the rules engine Internal helper function that delegates to evaluateForeignCalls and extracts the return value and type This function is used during rules processing to execute external contract calls and retrieve their results for rule evaluation
function _handleForeignCall(
    uint256 _policyId,
    bytes calldata _callingFunctionArgs,
    uint256 typeSpecificIndex,
    bytes[] memory retVals,
    ForeignCallEncodedIndex[] memory metadata
) internal returns (bytes memory, ParamTypes);
Parameters
NameTypeDescription
_policyIduint256The unique identifier of the policy associated with the foreign call
_callingFunctionArgsbytesArguments from the original function call, passed to the foreign call as needed
typeSpecificIndexuint256Index referencing the specific foreign call configuration to execute
retValsbytes[]Array containing previously computed return values that might be used as inputs for this call
metadataForeignCallEncodedIndex[]
Returns
NameTypeDescription
<none>bytesThe encoded return data from the foreign call
<none>ParamTypesThe parameter type of the foreign call’s return value

_handleGlobalVar

Handles global variables in the rules engine Internal function that processes global variable types and returns their encoded values with corresponding parameter types Used to access blockchain context variables like msg.sender, block.timestamp, etc. during rule evaluation
function _handleGlobalVar(uint256 globalVarType) internal view returns (bytes memory, ParamTypes);
Parameters
NameTypeDescription
globalVarTypeuint256An uint8 identifier representing which global variable to retrieve - GLOBAL_MSG_SENDER (1): The sender of the current call - GLOBAL_BLOCK_TIMESTAMP (2): Current block timestamp - GLOBAL_MSG_DATA (3): Complete calldata - GLOBAL_BLOCK_NUMBER (4): Current block number - GLOBAL_TX_ORIGIN (5): Original transaction sender
Returns
NameTypeDescription
<none>bytesbytes Encoded value of the requested global variable
<none>ParamTypesParameter type enum value corresponding to the global variable

_handleTrackerValue

Retrieves tracker values from storage based on policy ID and placeholder information Internal function that fetches either a regular tracker value or a mapped tracker value depending on the tracker’s configuration. For mapped trackers, it uses the placeholder’s mappedTrackerKey to fetch the specific value from the mapping.
function _handleTrackerValue(uint256 _policyId, Placeholder memory placeholder) internal view returns (bytes memory);
Parameters
NameTypeDescription
_policyIduint256The unique identifier of the policy containing the tracker
placeholderPlaceholderA Placeholder struct containing metadata about the tracker: - typeSpecificIndex: The ID of the tracker within the policy - mappedTrackerKey: The key to use for mapped trackers (ignored for regular trackers)
Returns
NameTypeDescription
<none>bytesbytes The encoded value of the requested tracker

_handleRegularParameter

Extracts function parameters from calldata based on placeholder type information *Internal pure function that handles different parameter types and retrieves their values from calldata
  • For dynamic types (strings, bytes): calls _getDynamicVariableFromCalldata to follow offsets
  • For arrays: extracts the length from the offset indicated in calldata
  • For value types: extracts 32 bytes directly from the specified position*
function _handleRegularParameter(bytes calldata _callingFunctionArgs, Placeholder memory placeholder)
    internal
    pure
    returns (bytes memory);
Parameters
NameTypeDescription
_callingFunctionArgsbytesThe raw calldata containing encoded function arguments
placeholderPlaceholderA Placeholder struct containing: - pType: Parameter type enum indicating how to decode the data - typeSpecificIndex: Position in calldata to read from (slot index for value types)
Returns
NameTypeDescription
<none>bytesbytes The extracted parameter value as bytes (must be decoded according to pType)

_doEffects

Internal function to process the effects of a rule.
function _doEffects(
    Rule storage _rule,
    uint256 _policyId,
    Effect[] memory _effects,
    bytes calldata _callingFunctionArgs,
    PlaceholderType _kind
) internal;
Parameters
NameTypeDescription
_ruleRuleThe rule being processed, stored in the contract’s storage.
_policyIduint256The ID of the policy associated with the rule.
_effectsEffect[]An array of effects to be applied as part of the rule execution.
_callingFunctionArgsbytesEncoded calldata containing arguments for the calling function.
_kindPlaceholderType

_buildEvent

Define event to be fired
function _buildEvent(
    Rule storage _rule,
    bool _isDynamicParam,
    uint256 _policyId,
    bytes32 _message,
    Effect memory _effectStruct,
    bytes calldata _callingFunctionArgs,
    PlaceholderType _kind
) internal;
Parameters
NameTypeDescription
_ruleRulethe rule struct event is associated to
_isDynamicParamboolstatic or dynamic event parameters
_policyIduint256policy Id
_messagebytes32Event Message String
_effectStructEffecteffect struct
_callingFunctionArgsbytescalling function arguments
_kindPlaceholderType

_fireDynamicEvent

Fire dynamic Event
function _fireDynamicEvent(
    Rule storage _rule,
    uint256 _policyId,
    bytes32 _message,
    bytes calldata _callingFunctionArgs,
    PlaceholderType _kind
) internal;
Parameters
NameTypeDescription
_ruleRulethe rule struct event is associated to
_policyIduint256policy Id
_messagebytes32Event Message String
_callingFunctionArgsbytescalling function arguments
_kindPlaceholderType

_fireEvent

Internal function to trigger an event based on the provided policy ID, message, and effect structure.
function _fireEvent(uint256 _policyId, bytes32 _message, Effect memory _effectStruct) internal;
Parameters
NameTypeDescription
_policyIduint256The unique identifier of the policy associated with the event.
_messagebytes32A bytes32 message that provides context or details about the event.
_effectStructEffectA struct containing the effect data to be processed during the event.

_evaluateExpression

Evaluate an effect expression
function _evaluateExpression(
    Rule storage _rule,
    uint256 _policyId,
    bytes calldata _callingFunctionArgs,
    uint256[] memory _instructionSet,
    PlaceholderType _kind
) internal;
Parameters
NameTypeDescription
_ruleRulethe rule structure containing the instruction set, with placeholders, to execute
_policyIduint256the policy id
_callingFunctionArgsbytesarguments of the calling function
_instructionSetuint256[]instruction set
_kindPlaceholderTypethe type of placeholders to build

_doRevert

Internal pure function to revert the transaction with a custom error message.
function _doRevert(string memory _message) internal pure;
Parameters
NameTypeDescription
_messagestringThe custom error message to include in the revert.

_getDynamicVariableFromCalldata

Extracts a dynamic variable from the provided calldata at the specified index. This function is a pure function and does not modify state.
function _getDynamicVariableFromCalldata(bytes calldata _data, uint256 _index) internal pure returns (bytes memory);
Parameters
NameTypeDescription
_databytesThe calldata containing the dynamic variables.
_indexuint256The index of the dynamic variable to extract.
Returns
NameTypeDescription
<none>bytesThe extracted dynamic variable as a bytes array.

_getDynamicValueArrayData

Retrieves a portion of dynamic value array data from the provided inputs. This function extracts a segment of dynamic data based on the specified length and offset.
function _getDynamicValueArrayData(
    bytes calldata _data,
    bytes memory _dynamicData,
    uint256 _length,
    uint256 _lengthToAppend,
    uint256 _offset
) internal pure returns (bytes memory, uint256);
Parameters
NameTypeDescription
_databytesThe calldata input containing the original data.
_dynamicDatabytesThe memory input containing the dynamic data to process.
_lengthuint256The total length of the dynamic data array.
_lengthToAppenduint256The length of data to append to the result.
_offsetuint256The starting position in the dynamic data array to begin extraction.
Returns
NameTypeDescription
<none>bytesA tuple containing: - A bytes memory object representing the extracted data. - A uint256 value indicating the updated offset after extraction.
<none>uint256