Verified contractExactMIT AND Apache-2.0
ChainlinkPriceRuleEnforcer
Address0x4daebf9c5813eff2606acd41ba25e57841e7cb75
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.23
- Same code
Only this contract
Details
- Compiler
- solc 0.8.23+commit.f704f362
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- london
- License
- MIT AND Apache-2.0
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,149,718
- Creation transaction
- 0xe64a62c0e6…a876fd015c
10 files
- src/enforcers/ChainlinkPriceRuleEnforcer.solmain6.98 KB
- lib/account-abstraction/contracts/interfaces/PackedUserOperation.sol1.47 KB
- lib/erc7579-implementation/src/interfaces/IERC7579Account.sol4.95 KB
- lib/erc7579-implementation/src/lib/ModeLib.sol5.69 KB
- src/enforcers/CaveatEnforcer.sol2.43 KB
- src/interfaces/IAggregatorV3.sol1.75 KB
- src/interfaces/ICaveatEnforcer.sol4.51 KB
- src/libraries/ChainlinkPriceRuleLib.sol6.19 KB
- src/utils/Constants.sol692 B
- src/utils/Types.sol1.59 KB
src/enforcers/ChainlinkPriceRuleEnforcer.sol
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.8.23;
import { CaveatEnforcer } from "./CaveatEnforcer.sol";
import { ChainlinkPriceRuleLib } from "../libraries/ChainlinkPriceRuleLib.sol";
import { IAggregatorV3 } from "../interfaces/IAggregatorV3.sol";
import { ModeCode } from "../utils/Types.sol";
/**
* @title ChainlinkPriceRuleEnforcer
* @notice Gates a delegation's redemption on a Chainlink price condition.
* @dev Supports four rule kinds (see `ChainlinkPriceRuleLib` RULE_KIND_* constants):
* - Dip (0): price fell >= thresholdBps over <= windowSeconds
* - Rise (1): price rose >= thresholdBps over <= windowSeconds
* - AbsoluteGte (2): current price >= triggerPrice
* - AbsoluteLte (3): current price <= triggerPrice
*
* The current price is always read from `latestRoundData()` on `terms.priceFeed` (never from args).
* The reference price (for relative rules) is read from `getRoundData(args.referenceRoundId)`,
* with `updatedAt` validated against the user-specified time window.
*
* This enforcer operates only in single execution call type and with default execution mode.
* `afterHook` is a no-op; the price check is pre-execution only and writes no state.
*
* @custom:assumptions
* - `msg.sender` is expected to be the DelegationManager (consistent with other enforcers).
* - The pinned `priceFeed` must be a trusted Chainlink proxy. v1 does NOT validate the feed address
* against a registry. Integrators building delegation-construction UIs MUST hard-verify the feed
* address (e.g. against the Chainlink feeds list at https://docs.chain.link/data-feeds/price-feeds/addresses)
* before presenting terms to the user for signing. A malicious feed address completely bypasses
* all price checks and allows the redeemer to trigger the rule at will.
* - On L2s, consider also using a sequencer uptime feed; this enforcer only checks `maxStaleSeconds`.
*/
contract ChainlinkPriceRuleEnforcer is CaveatEnforcer {
using ChainlinkPriceRuleLib for ChainlinkPriceRuleLib.Terms;
////////////////////////////// Public Methods //////////////////////////////
/**
* @notice Hook called before execution; reverts if the price rule is not satisfied.
* @param _terms 68-byte packed terms (see `ChainlinkPriceRuleLib.decodeTerms`).
* @param _args abi.encode(uint80 referenceRoundId); `referenceRoundId` is ignored for absolute rules.
*/
function beforeHook(
bytes calldata _terms,
bytes calldata _args,
ModeCode _mode,
bytes calldata,
bytes32,
address,
address
)
public
override
onlySingleCallTypeMode(_mode)
onlyDefaultExecutionMode(_mode)
{
ChainlinkPriceRuleLib.Terms memory terms_ = ChainlinkPriceRuleLib.decodeTerms(_terms);
terms_.validateTerms();
uint80 referenceRoundId_ = abi.decode(_args, (uint80));
IAggregatorV3 feed_ = IAggregatorV3(terms_.priceFeed);
// Validate feed decimals match what the delegator pinned in terms.
require(
feed_.decimals() == terms_.expectedDecimals,
"ChainlinkPriceRuleEnforcer:decimals-mismatch"
);
(
uint80 roundIdNow_,
int256 priceNow_,
,
uint256 updatedAtNow_,
uint80 answeredInRoundNow_
) = feed_.latestRoundData();
require(priceNow_ > 0, "ChainlinkPriceRuleEnforcer:invalid-current-price");
require(updatedAtNow_ > 0, "ChainlinkPriceRuleEnforcer:invalid-updated-at-now");
require(
block.timestamp - updatedAtNow_ <= terms_.maxStaleSeconds,
"ChainlinkPriceRuleEnforcer:stale-current-price"
);
require(
answeredInRoundNow_ >= roundIdNow_,
"ChainlinkPriceRuleEnforcer:stale-current-round"
);
if (ChainlinkPriceRuleLib.isRelativeRule(terms_.ruleKind)) {
_enforceRelativeRule(terms_, feed_, referenceRoundId_, priceNow_, roundIdNow_);
} else {
_enforceAbsoluteRule(terms_, priceNow_);
}
}
/**
* @notice No-op afterHook; price checks are pre-execution only.
*/
function afterHook(
bytes calldata,
bytes calldata,
ModeCode _mode,
bytes calldata,
bytes32,
address,
address
)
public
override
onlySingleCallTypeMode(_mode)
onlyDefaultExecutionMode(_mode)
{ }
/**
* @notice Decodes terms for inspection.
*/
function getTermsInfo(bytes calldata _terms)
public
pure
returns (ChainlinkPriceRuleLib.Terms memory terms_)
{
return ChainlinkPriceRuleLib.decodeTerms(_terms);
}
////////////////////////////// Internal Methods //////////////////////////////
function _enforceRelativeRule(
ChainlinkPriceRuleLib.Terms memory _terms,
IAggregatorV3 _feed,
uint80 _referenceRoundId,
int256 _priceNow,
uint80 _roundIdNow
)
private
view
{
require(_referenceRoundId != 0, "ChainlinkPriceRuleEnforcer:invalid-reference-round-id");
require(
_referenceRoundId < _roundIdNow,
"ChainlinkPriceRuleEnforcer:reference-not-older"
);
(
,
int256 priceRef_,
,
uint256 updatedAtRef_,
uint80 answeredInRoundRef_
) = _feed.getRoundData(_referenceRoundId);
require(priceRef_ > 0, "ChainlinkPriceRuleEnforcer:invalid-reference-price");
require(
answeredInRoundRef_ >= _referenceRoundId,
"ChainlinkPriceRuleEnforcer:stale-reference-round"
);
// Reference round must be within the user-specified window: updatedAtRef >= now - windowSeconds.
require(
updatedAtRef_ >= block.timestamp - _terms.windowSeconds,
"ChainlinkPriceRuleEnforcer:reference-outside-window"
);
// Anti-noise: reference round must be at least minGapSeconds old.
// When minGapSeconds == 0, this reduces to updatedAtRef <= block.timestamp (blocks future timestamps).
require(
updatedAtRef_ <= block.timestamp - _terms.minGapSeconds,
"ChainlinkPriceRuleEnforcer:reference-too-recent"
);
require(
ChainlinkPriceRuleLib.meetsRelativeRule(_terms.ruleKind, _priceNow, priceRef_, _terms.thresholdBps),
"ChainlinkPriceRuleEnforcer:price-rule-not-met"
);
}
function _enforceAbsoluteRule(ChainlinkPriceRuleLib.Terms memory _terms, int256 _priceNow) private pure {
require(
ChainlinkPriceRuleLib.meetsAbsoluteRule(_terms.ruleKind, _priceNow, _terms.triggerPrice),
"ChainlinkPriceRuleEnforcer:price-rule-not-met"
);
}
}
lib/account-abstraction/contracts/interfaces/PackedUserOperation.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.5;
/**
* User Operation struct
* @param sender - The sender account of this request.
* @param nonce - Unique value the sender uses to verify it is not a replay.
* @param initCode - If set, the account contract will be created by this constructor/
* @param callData - The method call to execute on this account.
* @param accountGasLimits - Packed gas limits for validateUserOp and gas limit passed to the callData method call.
* @param preVerificationGas - Gas not calculated by the handleOps method, but added to the gas paid.
* Covers batch overhead.
* @param gasFees - packed gas fields maxPriorityFeePerGas and maxFeePerGas - Same as EIP-1559 gas parameters.
* @param paymasterAndData - If set, this field holds the paymaster address, verification gas limit, postOp gas limit and paymaster-specific extra data
* The paymaster will pay for the transaction instead of the sender.
* @param signature - Sender-verified signature over the entire request, the EntryPoint address and the chain ID.
*/
struct PackedUserOperation {
address sender;
uint256 nonce;
bytes initCode;
bytes callData;
bytes32 accountGasLimits;
uint256 preVerificationGas;
bytes32 gasFees;
bytes paymasterAndData;
bytes signature;
}
lib/erc7579-implementation/src/interfaces/IERC7579Account.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
import { CallType, ExecType, ModeCode } from "../lib/ModeLib.sol";
struct Execution {
address target;
uint256 value;
bytes callData;
}
interface IERC7579Account {
event ModuleInstalled(uint256 moduleTypeId, address module);
event ModuleUninstalled(uint256 moduleTypeId, address module);
/**
* @dev Executes a transaction on behalf of the account.
* This function is intended to be called by ERC-4337 EntryPoint.sol
* @dev Ensure adequate authorization control: i.e. onlyEntryPointOrSelf
*
* @dev MSA MUST implement this function signature.
* If a mode is requested that is not supported by the Account, it MUST revert
* @param mode The encoded execution mode of the transaction. See ModeLib.sol for details
* @param executionCalldata The encoded execution call data
*/
function execute(ModeCode mode, bytes calldata executionCalldata) external payable;
/**
* @dev Executes a transaction on behalf of the account.
* This function is intended to be called by Executor Modules
* @dev Ensure adequate authorization control: i.e. onlyExecutorModule
*
* @dev MSA MUST implement this function signature.
* If a mode is requested that is not supported by the Account, it MUST revert
* @param mode The encoded execution mode of the transaction. See ModeLib.sol for details
* @param executionCalldata The encoded execution call data
*/
function executeFromExecutor(
ModeCode mode,
bytes calldata executionCalldata
)
external
payable
returns (bytes[] memory returnData);
/**
* @dev ERC-1271 isValidSignature
* This function is intended to be used to validate a smart account signature
* and may forward the call to a validator module
*
* @param hash The hash of the data that is signed
* @param data The data that is signed
*/
function isValidSignature(bytes32 hash, bytes calldata data) external view returns (bytes4);
/**
* @dev installs a Module of a certain type on the smart account
* @dev Implement Authorization control of your chosing
* @param moduleTypeId the module type ID according the ERC-7579 spec
* @param module the module address
* @param initData arbitrary data that may be required on the module during `onInstall`
* initialization.
*/
function installModule(
uint256 moduleTypeId,
address module,
bytes calldata initData
)
external
payable;
/**
* @dev uninstalls a Module of a certain type on the smart account
* @dev Implement Authorization control of your chosing
* @param moduleTypeId the module type ID according the ERC-7579 spec
* @param module the module address
* @param deInitData arbitrary data that may be required on the module during `onUninstall`
* de-initialization.
*/
function uninstallModule(
uint256 moduleTypeId,
address module,
bytes calldata deInitData
)
external
payable;
/**
* Function to check if the account supports a certain CallType or ExecType (see ModeLib.sol)
* @param encodedMode the encoded mode
*/
function supportsExecutionMode(ModeCode encodedMode) external view returns (bool);
/**
* Function to check if the account supports installation of a certain module type Id
* @param moduleTypeId the module type ID according the ERC-7579 spec
*/
function supportsModule(uint256 moduleTypeId) external view returns (bool);
/**
* Function to check if the account has a certain module installed
* @param moduleTypeId the module type ID according the ERC-7579 spec
* Note: keep in mind that some contracts can be multiple module types at the same time. It
* thus may be necessary to query multiple module types
* @param module the module address
* @param additionalContext additional context data that the smart account may interpret to
* identifiy conditions under which the module is installed.
* usually this is not necessary, but for some special hooks that
* are stored in mappings, this param might be needed
*/
function isModuleInstalled(
uint256 moduleTypeId,
address module,
bytes calldata additionalContext
)
external
view
returns (bool);
/**
* @dev Returns the account id of the smart account
* @return accountImplementationId the account id of the smart account
* the accountId should be structured like so:
* "vendorname.accountname.semver"
*/
function accountId() external view returns (string memory accountImplementationId);
}
lib/erc7579-implementation/src/lib/ModeLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
/**
* @title ModeLib
* To allow smart accounts to be very simple, but allow for more complex execution, A custom mode
* encoding is used.
* Function Signature of execute function:
* function execute(ModeCode mode, bytes calldata executionCalldata) external payable;
* This allows for a single bytes32 to be used to encode the execution mode, calltype, execType and
* context.
* NOTE: Simple Account implementations only have to scope for the most significant byte. Account that
* implement
* more complex execution modes may use the entire bytes32.
*
* |--------------------------------------------------------------------|
* | CALLTYPE | EXECTYPE | UNUSED | ModeSelector | ModePayload |
* |--------------------------------------------------------------------|
* | 1 byte | 1 byte | 4 bytes | 4 bytes | 22 bytes |
* |--------------------------------------------------------------------|
*
* CALLTYPE: 1 byte
* CallType is used to determine how the executeCalldata paramter of the execute function has to be
* decoded.
* It can be either single, batch or delegatecall. In the future different calls could be added.
* CALLTYPE can be used by a validation module to determine how to decode <userOp.callData[36:]>.
*
* EXECTYPE: 1 byte
* ExecType is used to determine how the account should handle the execution.
* It can indicate if the execution should revert on failure or continue execution.
* In the future more execution modes may be added.
* Default Behavior (EXECTYPE = 0x00) is to revert on a single failed execution. If one execution in
* a batch fails, the entire batch is reverted
*
* UNUSED: 4 bytes
* Unused bytes are reserved for future use.
*
* ModeSelector: bytes4
* The "optional" mode selector can be used by account vendors, to implement custom behavior in
* their accounts.
* the way a ModeSelector is to be calculated is bytes4(keccak256("vendorname.featurename"))
* this is to prevent collisions between different vendors, while allowing innovation and the
* development of new features without coordination between ERC-7579 implementing accounts
*
* ModePayload: 22 bytes
* Mode payload is used to pass additional data to the smart account execution, this may be
* interpreted depending on the ModeSelector
*
* ExecutionCallData: n bytes
* single, delegatecall or batch exec abi.encoded as bytes
*/
import { Execution } from "../interfaces/IERC7579Account.sol";
// Custom type for improved developer experience
type ModeCode is bytes32;
type CallType is bytes1;
type ExecType is bytes1;
type ModeSelector is bytes4;
type ModePayload is bytes22;
// Default CallType
CallType constant CALLTYPE_SINGLE = CallType.wrap(0x00);
// Batched CallType
CallType constant CALLTYPE_BATCH = CallType.wrap(0x01);
// @dev Implementing delegatecall is OPTIONAL!
// implement delegatecall with extreme care.
CallType constant CALLTYPE_STATIC = CallType.wrap(0xFE);
CallType constant CALLTYPE_DELEGATECALL = CallType.wrap(0xFF);
// @dev default behavior is to revert on failure
// To allow very simple accounts to use mode encoding, the default behavior is to revert on failure
// Since this is value 0x00, no additional encoding is required for simple accounts
ExecType constant EXECTYPE_DEFAULT = ExecType.wrap(0x00);
// @dev account may elect to change execution behavior. For example "try exec" / "allow fail"
ExecType constant EXECTYPE_TRY = ExecType.wrap(0x01);
ModeSelector constant MODE_DEFAULT = ModeSelector.wrap(bytes4(0x00000000));
// Example declaration of a custom mode selector
ModeSelector constant MODE_OFFSET = ModeSelector.wrap(bytes4(keccak256("default.mode.offset")));
/**
* @dev ModeLib is a helper library to encode/decode ModeCodes
*/
library ModeLib {
function decode(ModeCode mode)
internal
pure
returns (
CallType _calltype,
ExecType _execType,
ModeSelector _modeSelector,
ModePayload _modePayload
)
{
assembly {
_calltype := mode
_execType := shl(8, mode)
_modeSelector := shl(48, mode)
_modePayload := shl(80, mode)
}
}
function encode(
CallType callType,
ExecType execType,
ModeSelector mode,
ModePayload payload
)
internal
pure
returns (ModeCode)
{
return ModeCode.wrap(
bytes32(
abi.encodePacked(callType, execType, bytes4(0), ModeSelector.unwrap(mode), payload)
)
);
}
function encodeSimpleBatch() internal pure returns (ModeCode mode) {
mode = encode(CALLTYPE_BATCH, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function encodeSimpleSingle() internal pure returns (ModeCode mode) {
mode = encode(CALLTYPE_SINGLE, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function getCallType(ModeCode mode) internal pure returns (CallType calltype) {
assembly {
calltype := mode
}
}
}
using { eqModeSelector as == } for ModeSelector global;
using { eqCallType as == } for CallType global;
using { eqExecType as == } for ExecType global;
function eqCallType(CallType a, CallType b) pure returns (bool) {
return CallType.unwrap(a) == CallType.unwrap(b);
}
function eqExecType(ExecType a, ExecType b) pure returns (bool) {
return ExecType.unwrap(a) == ExecType.unwrap(b);
}
function eqModeSelector(ModeSelector a, ModeSelector b) pure returns (bool) {
return ModeSelector.unwrap(a) == ModeSelector.unwrap(b);
}
src/enforcers/CaveatEnforcer.sol
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.8.23;
import { ModeLib } from "@erc7579/lib/ModeLib.sol";
import { ICaveatEnforcer } from "../interfaces/ICaveatEnforcer.sol";
import { ModeCode, ExecType } from "../utils/Types.sol";
import { CALLTYPE_SINGLE, CALLTYPE_BATCH, EXECTYPE_DEFAULT, EXECTYPE_TRY } from "../utils/Constants.sol";
/**
* @title CaveatEnforcer
* @dev This abstract contract enforces caveats before and after the execution of an execution.
*/
abstract contract CaveatEnforcer is ICaveatEnforcer {
using ModeLib for ModeCode;
/// @inheritdoc ICaveatEnforcer
function beforeAllHook(bytes calldata, bytes calldata, ModeCode, bytes calldata, bytes32, address, address) public virtual { }
/// @inheritdoc ICaveatEnforcer
function beforeHook(bytes calldata, bytes calldata, ModeCode, bytes calldata, bytes32, address, address) public virtual { }
/// @inheritdoc ICaveatEnforcer
function afterHook(bytes calldata, bytes calldata, ModeCode, bytes calldata, bytes32, address, address) public virtual { }
/// @inheritdoc ICaveatEnforcer
function afterAllHook(bytes calldata, bytes calldata, ModeCode, bytes calldata, bytes32, address, address) public virtual { }
/**
* @dev Require the function call to be in single call type
*/
modifier onlySingleCallTypeMode(ModeCode _mode) {
{
require(ModeLib.getCallType(_mode) == CALLTYPE_SINGLE, "CaveatEnforcer:invalid-call-type");
}
_;
}
/**
* @dev Require the function call to be in batch call type
*/
modifier onlyBatchCallTypeMode(ModeCode _mode) {
{
require(ModeLib.getCallType(_mode) == CALLTYPE_BATCH, "CaveatEnforcer:invalid-call-type");
}
_;
}
/**
* @dev Require the function call to be in default execution mode
*/
modifier onlyDefaultExecutionMode(ModeCode _mode) {
{
(, ExecType _execType,,) = _mode.decode();
require(_execType == EXECTYPE_DEFAULT, "CaveatEnforcer:invalid-execution-type");
}
_;
}
/**
* @dev Require the function call to be in try execution mode
*/
modifier onlyTryExecutionMode(ModeCode _mode) {
{
(, ExecType _execType,,) = _mode.decode();
require(_execType == EXECTYPE_TRY, "CaveatEnforcer:invalid-execution-type");
}
_;
}
}
src/interfaces/IAggregatorV3.sol
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.8.23;
/**
* @title IAggregatorV3
* @notice Minimal inlined subset of Chainlink `AggregatorV3Interface` for reading price feed rounds.
* @dev Pin the proxy address (not the underlying aggregator) in caveat terms so upgrades do not affect consumers.
* Reference: https://docs.chain.link/data-feeds/api-reference
*/
interface IAggregatorV3 {
/**
* @notice Returns the decimals of the feed (e.g. 8 for USD pairs).
*/
function decimals() external view returns (uint8);
/**
* @notice Returns the latest round data.
* @return roundId_ The round ID.
* @return answer_ The price for the round (scaled by `decimals()`).
* @return startedAt_ Timestamp when the round started.
* @return updatedAt_ Timestamp when the round was last updated.
* @return answeredInRound_ The round ID in which the answer was computed.
*/
function latestRoundData()
external
view
returns (uint80 roundId_, int256 answer_, uint256 startedAt_, uint256 updatedAt_, uint80 answeredInRound_);
/**
* @notice Returns the round data for a specific round ID.
* @param _roundId The round ID to query.
* @return roundId_ The round ID.
* @return answer_ The price for the round (scaled by `decimals()`).
* @return startedAt_ Timestamp when the round started.
* @return updatedAt_ Timestamp when the round was last updated.
* @return answeredInRound_ The round ID in which the answer was computed.
*/
function getRoundData(uint80 _roundId)
external
view
returns (uint80 roundId_, int256 answer_, uint256 startedAt_, uint256 updatedAt_, uint80 answeredInRound_);
}
src/interfaces/ICaveatEnforcer.sol
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.8.23;
import { ModeCode } from "../utils/Types.sol";
/**
* @title CaveatEnforcer
* @notice This is an abstract contract that exposes pre and post Execution hooks during delegation redemption.
* @dev Hooks can be used to enforce conditions before and after an Execution is performed.
* @dev Reverting during the hooks will revert the entire delegation redemption.
* @dev Child contracts can implement the beforeAllHook, beforeHook, afterAllHook, afterHook methods.
* @dev NOTE: There is no guarantee that the Execution is performed. If you are relying on the execution then
* be sure to use the `afterHook` or `afterAllHook` methods to validate any required conditions.
*/
interface ICaveatEnforcer {
/**
* @notice Enforces conditions before any actions in a batch redemption process begin.
* @dev This function MUST revert if the conditions are not met.
* @param _terms The terms to enforce set by the delegator.
* @param _args An optional input parameter set by the redeemer at time of invocation.
* @param _mode The mode of execution for the executionCalldata.
* @param _executionCalldata The data representing the execution.
* @param _delegationHash The hash of the delegation.
* @param _delegator The address of the delegator.
* @param _redeemer The address that is redeeming the delegation.
*/
function beforeAllHook(
bytes calldata _terms,
bytes calldata _args,
ModeCode _mode,
bytes calldata _executionCalldata,
bytes32 _delegationHash,
address _delegator,
address _redeemer
)
external;
/**
* @notice Enforces conditions before the execution tied to a specific delegation in the redemption process.
* @dev This function MUST revert if the conditions are not met.
* @param _terms The terms to enforce set by the delegator.
* @param _args An optional input parameter set by the redeemer at time of invocation.
* @param _mode The mode of execution for the executionCalldata.
* @param _executionCalldata The data representing the execution.
* @param _delegationHash The hash of the delegation.
* @param _delegator The address of the delegator.
* @param _redeemer The address that is redeeming the delegation.
*/
function beforeHook(
bytes calldata _terms,
bytes calldata _args,
ModeCode _mode,
bytes calldata _executionCalldata,
bytes32 _delegationHash,
address _delegator,
address _redeemer
)
external;
/**
* @notice Enforces conditions after the execution tied to a specific delegation in the redemption process.
* @dev This function MUST revert if the conditions are not met.
* @param _terms The terms to enforce set by the delegator.
* @param _args An optional input parameter set by the redeemer at time of invocation.
* @param _mode The mode of execution for the executionCalldata.
* @param _executionCalldata The data representing the execution.
* @param _delegationHash The hash of the delegation.
* @param _delegator The address of the delegator.
* @param _redeemer The address that is redeeming the delegation.
*/
function afterHook(
bytes calldata _terms,
bytes calldata _args,
ModeCode _mode,
bytes calldata _executionCalldata,
bytes32 _delegationHash,
address _delegator,
address _redeemer
)
external;
/**
* @notice Enforces conditions after all actions in a batch redemption process have been executed.
* @dev This function MUST revert if the conditions are not met.
* @param _terms The terms to enforce set by the delegator.
* @param _args An optional input parameter set by the redeemer at time of invocation.
* @param _mode The mode of execution for the executionCalldata.
* @param _executionCalldata The data representing the execution.
* @param _delegationHash The hash of the delegation.
* @param _delegator The address of the delegator.
* @param _redeemer The address that is redeeming the delegation.
*/
function afterAllHook(
bytes calldata _terms,
bytes calldata _args,
ModeCode _mode,
bytes calldata _executionCalldata,
bytes32 _delegationHash,
address _delegator,
address _redeemer
)
external;
}
src/libraries/ChainlinkPriceRuleLib.sol
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.8.23;
/**
* @title ChainlinkPriceRuleLib
* @notice Shared types and helpers for Chainlink price-rule caveat enforcers.
* @dev Terms are packed via `abi.encodePacked` and signed by the delegator at grant time.
* The enforcer reads the current price from `latestRoundData()` (never from args) and the
* reference price from `getRoundData(args.referenceRoundId)`, validating the reference
* round's `updatedAt` against the user-specified time window.
*/
library ChainlinkPriceRuleLib {
uint256 internal constant BPS_DENOMINATOR = 10_000;
uint256 internal constant TERMS_LENGTH = 68;
/**
* @notice Rule kind controlling how prices are compared.
* @dev Values are stored as `uint8` at terms offset 20. Using `uint8` (not the enum) in `Terms` avoids
* reverts during `decodeTerms` when an out-of-range value is supplied; `validateTerms` checks the range.
*/
uint8 internal constant RULE_KIND_DIP = 0;
uint8 internal constant RULE_KIND_RISE = 1;
uint8 internal constant RULE_KIND_ABSOLUTE_GTE = 2;
uint8 internal constant RULE_KIND_ABSOLUTE_LTE = 3;
/**
* @notice Packed terms (68 bytes) pinned by the delegator at grant time.
* @dev Layout:
* offset 0 : priceFeed (20 bytes, address)
* offset 20 : ruleKind (1 byte, uint8) — see RULE_KIND_* constants
* offset 21 : expectedDecimals (1 byte, uint8) — must match feed.decimals()
* offset 22 : windowSeconds (4 bytes, uint32)
* offset 26 : thresholdBps (2 bytes, uint16)
* offset 28 : maxStaleSeconds (4 bytes, uint32)
* offset 32 : minGapSeconds (4 bytes, uint32)
* offset 36 : triggerPrice (32 bytes, int256)
*/
struct Terms {
address priceFeed;
uint8 ruleKind;
uint8 expectedDecimals;
uint32 windowSeconds;
uint16 thresholdBps;
uint32 maxStaleSeconds;
uint32 minGapSeconds;
int256 triggerPrice;
}
function encodeTerms(Terms memory _terms) internal pure returns (bytes memory terms_) {
terms_ = abi.encodePacked(
_terms.priceFeed,
uint8(_terms.ruleKind),
uint8(_terms.expectedDecimals),
_terms.windowSeconds,
_terms.thresholdBps,
_terms.maxStaleSeconds,
_terms.minGapSeconds,
_terms.triggerPrice
);
}
function decodeTerms(bytes calldata _terms) internal pure returns (Terms memory terms_) {
require(_terms.length == TERMS_LENGTH, "ChainlinkPriceRuleLib:invalid-terms-length");
terms_.priceFeed = address(bytes20(_terms[0:20]));
terms_.ruleKind = uint8(_terms[20]);
terms_.expectedDecimals = uint8(_terms[21]);
terms_.windowSeconds = uint32(bytes4(_terms[22:26]));
terms_.thresholdBps = uint16(bytes2(_terms[26:28]));
terms_.maxStaleSeconds = uint32(bytes4(_terms[28:32]));
terms_.minGapSeconds = uint32(bytes4(_terms[32:36]));
terms_.triggerPrice = int256(uint256(bytes32(_terms[36:68])));
}
/**
* @notice Validates terms at grant and execution time.
* @dev Reverts on invalid configuration. Relative rules require a positive window and threshold;
* absolute rules require a non-zero trigger price; `maxStaleSeconds` must be positive.
*/
function validateTerms(Terms memory _terms) internal pure {
require(_terms.priceFeed != address(0), "ChainlinkPriceRuleLib:invalid-zero-price-feed");
require(_terms.ruleKind <= RULE_KIND_ABSOLUTE_LTE, "ChainlinkPriceRuleLib:invalid-rule-kind");
require(_terms.maxStaleSeconds > 0, "ChainlinkPriceRuleLib:invalid-zero-max-stale");
require(
_terms.expectedDecimals > 0 && _terms.expectedDecimals <= 18,
"ChainlinkPriceRuleLib:invalid-decimals"
);
if (_terms.ruleKind == RULE_KIND_DIP || _terms.ruleKind == RULE_KIND_RISE) {
require(_terms.windowSeconds > 0, "ChainlinkPriceRuleLib:invalid-zero-window");
require(_terms.thresholdBps > 0, "ChainlinkPriceRuleLib:invalid-zero-threshold");
require(
_terms.thresholdBps < BPS_DENOMINATOR,
"ChainlinkPriceRuleLib:invalid-threshold-bps"
);
} else {
require(_terms.triggerPrice > 0, "ChainlinkPriceRuleLib:invalid-zero-trigger");
}
}
/**
* @notice Returns true if `priceNow` satisfies the relative rule vs `priceRef`.
* @dev Caller must ensure `priceRef > 0`. Uses unsigned math on int256 values known to be positive.
*/
function meetsRelativeRule(
uint8 _ruleKind,
int256 _priceNow,
int256 _priceRef,
uint16 _thresholdBps
)
internal
pure
returns (bool)
{
uint256 priceNow_ = uint256(_priceNow);
uint256 priceRef_ = uint256(_priceRef);
if (_ruleKind == RULE_KIND_DIP) {
if (priceNow_ >= priceRef_) return false;
uint256 dropBps_ = ((priceRef_ - priceNow_) * BPS_DENOMINATOR) / priceRef_;
return dropBps_ >= uint256(_thresholdBps);
} else if (_ruleKind == RULE_KIND_RISE) {
if (priceNow_ <= priceRef_) return false;
uint256 riseBps_ = ((priceNow_ - priceRef_) * BPS_DENOMINATOR) / priceRef_;
return riseBps_ >= uint256(_thresholdBps);
}
return false;
}
/**
* @notice Returns true if `priceNow` satisfies the absolute rule vs `triggerPrice`.
*/
function meetsAbsoluteRule(uint8 _ruleKind, int256 _priceNow, int256 _triggerPrice) internal pure returns (bool) {
if (_ruleKind == RULE_KIND_ABSOLUTE_GTE) {
return _priceNow >= _triggerPrice;
} else if (_ruleKind == RULE_KIND_ABSOLUTE_LTE) {
return _priceNow <= _triggerPrice;
}
return false;
}
function isRelativeRule(uint8 _ruleKind) internal pure returns (bool) {
return _ruleKind == RULE_KIND_DIP || _ruleKind == RULE_KIND_RISE;
}
}
src/utils/Constants.sol
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.8.23;
import {
CALLTYPE_SINGLE, CALLTYPE_BATCH, EXECTYPE_DEFAULT, EXECTYPE_TRY, MODE_DEFAULT, MODE_OFFSET
} from "@erc7579/lib/ModeLib.sol";
bytes32 constant EIP712_DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// NOTE: signature is omitted from the Delegation typehash
bytes32 constant DELEGATION_TYPEHASH = keccak256(
"Delegation(address delegate,address delegator,bytes32 authority,Caveat[] caveats,uint256 salt)Caveat(address enforcer,bytes terms)"
);
bytes32 constant CAVEAT_TYPEHASH = keccak256("Caveat(address enforcer,bytes terms)");
src/utils/Types.sol
// SPDX-License-Identifier: MIT AND Apache-2.0
pragma solidity 0.8.23;
import { PackedUserOperation } from "@account-abstraction/interfaces/PackedUserOperation.sol";
import { Execution } from "@erc7579/interfaces/IERC7579Account.sol";
import { ModeCode, CallType, ExecType, ModeSelector, ModePayload } from "@erc7579/lib/ModeLib.sol";
/**
* @title EIP712Domain
* @notice Struct representing the EIP712 domain for signature validation.
*/
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
/**
* @title Delegation
* @notice Struct representing a delegation to give a delegate authority to act on behalf of a delegator.
* @dev `signature` is ignored during delegation hashing so it can be manipulated post signing.
*/
struct Delegation {
address delegate;
address delegator;
bytes32 authority;
Caveat[] caveats;
uint256 salt;
bytes signature;
}
/**
* @title Caveat
* @notice Struct representing a caveat to enforce on a delegation.
* @dev `args` is ignored during caveat hashing so it can be manipulated post signing.
*/
struct Caveat {
address enforcer;
bytes terms;
bytes args;
}
/**
* @title P256 Public Key
* @notice Struct containing the X and Y coordinates of a P256 public key.
*/
struct P256PublicKey {
uint256 x;
uint256 y;
}
struct DecodedWebAuthnSignature {
uint256 r;
uint256 s;
bytes authenticatorData;
bool requireUserVerification;
string clientDataJSONPrefix;
string clientDataJSONSuffix;
uint256 responseTypeLocation;
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "london",
"remappings": [
"@account-abstraction/=lib/account-abstraction/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-upgradable-contracts/contracts/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"forge-std/=lib/forge-std/src/",
"@solidity-stringutils/=lib/solidity-stringutils/src/",
"@bytes-utils/=lib/solidity-bytes-utils/contracts/",
"@FCL/=lib/FCL/solidity/src/",
"@erc7579/=lib/erc7579-implementation/src/",
"@SCL/=lib/SCL/src/",
"FreshCryptoLib/=lib/FreshCryptoLib/solidity/src/",
"@solidity/=lib/SCL/src/",
"FCL/=lib/FCL/solidity/src/",
"SCL/=lib/SCL/",
"account-abstraction/=lib/account-abstraction/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"erc7579-implementation/=lib/erc7579-implementation/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"sentinellist/=lib/erc7579-implementation/node_modules/@rhinestone/sentinellist/src/",
"solady/=lib/erc7579-implementation/node_modules/solady/src/",
"solidity-bytes-utils/=lib/solidity-bytes-utils/contracts/",
"solidity-stringutils/=lib/solidity-stringutils/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.