Проверенный контрактТочноеMIT
FraxSafeSetup
Адрес0xe60cd7ae5e4dc37da592a1d61a67c3bef5a79d99
- Баланс
0 ETH
- Транзакций
0
- Компилятор
solc 0.8.28
- Тот же код
Только этот контракт
Подробности
- Компилятор
- solc 0.8.28+commit.7893614a
- Язык
- solidity
- Оптимизация
- Да, 200 прогонов
- Версия EVM
- cancun
- Через IR
- да
- Лицензия
- MIT
- Совпадение
- Точноекод создания: да, код в сети: да
- Проверен на Sourcify
- Создан в блоке
- 26 428 657
- Транзакция создания
- 0xf18fdde3eb…65e3102fd7
7 файлов
src/FraxSafeSetup.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {ISafe} from "./interfaces/ISafe.sol";
import {FraxGuard} from "./FraxGuard.sol";
/// @title FraxSafeSetup
/// @notice Sets up a new Safe for FraxNet. Pass it as `to` and the encoded `enableFraxGuard` call as `data` to
/// Safe.setup, which delegatecalls it once the owners are set. In order, it:
/// 1. enables the RecoveryModule (the customers' exit),
/// 2. enables MultiChainSig (sign once, execute on every chain),
/// 3. installs FraxFallbackHandler (Frax required on EIP-1271 messages),
/// 4. configures FraxGuard,
/// 5. installs FraxGuard.
/// @dev Because all of this is part of the initializer, the counterfactual Safe address commits to it. Anyone
/// who deploys the same address on another chain gets the same protections. Cap tokens that have no code on
/// that chain are skipped by the guard rather than blocking the Safe.
contract FraxSafeSetup {
address private immutable SELF = address(this);
error OnlyDelegateCall();
function enableFraxGuard(address guard, FraxGuard.InitConfig calldata config) external {
if (address(this) == SELF) revert OnlyDelegateCall();
// Running in the Safe's context: these calls come from the Safe itself, which passes `authorized`.
ISafe safe = ISafe(address(this));
safe.enableModule(FraxGuard(guard).RECOVERY_MODULE());
safe.enableModule(FraxGuard(guard).MULTICHAIN_SIG());
safe.setFallbackHandler(FraxGuard(guard).FRAX_FALLBACK_HANDLER());
FraxGuard(guard).initialize(config);
safe.setGuard(guard);
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/FraxGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {ITransactionGuard, Operation} from "./interfaces/ITransactionGuard.sol";
import {ISafe} from "./interfaces/ISafe.sol";
import {SafeSignatures} from "./libraries/SafeSignatures.sol";
import {FraxApproval} from "./libraries/FraxApproval.sol";
/// @dev Immutables exposed by RecoveryModule and FraxFallbackHandler, checked for consistency at deployment.
interface IFraxDeployment {
function FRAX_SIGNER() external view returns (address);
function MULTISEND_CALL_ONLY() external view returns (address);
}
/// @title FraxGuard
/// @notice Onchain backstop for FraxNet Safes, as a Safe v1.4.1 transaction guard. Deploy one shared instance per
/// chain; every setting is per Safe and keyed by `msg.sender`.
/// @dev Checked on every execTransaction:
/// 1. Co-signer: if the Safe requires it, FraxSigner must be one of the signatures the Safe verified, and its
/// approval must name the Safe's committed policy hash.
/// 2. Delegatecall: only to MultiSendCallOnly. Every call inside the batch is checked like a top-level call.
/// 3. Calls to the Safe itself (owners, threshold, modules, guard, fallback handler) must have been scheduled
/// at least `configDelay` earlier.
/// 4. Approvals of a capped token can only go to an approved spender.
/// 5. Net outflow of each capped token is limited by an allowance that refills at `limit` per day, up to
/// `limit`. Outflow is the Safe's balance change across the whole transaction, so it does not depend on
/// decoding calldata.
/// Checked after every transaction:
/// 6. While FraxSigner is an owner, the threshold is at least 2, so FraxSigner alone can never execute.
/// 7. A Safe that requires the co-signer keeps FraxSigner as an owner, keeps the RecoveryModule enabled (the
/// customers' exit), and keeps FraxFallbackHandler (which requires Frax on EIP-1271 messages).
///
/// Guard settings follow one rule: changes that tighten apply immediately, and changes that loosen must be
/// scheduled first, using the same timelock as rule 3.
///
/// A Safe's settings belong to one installation of the guard. When a transaction removes or replaces the
/// guard, all of that Safe's settings are dropped, so a later installation starts from `initialize`.
///
/// MultiChainSig transactions get the same checks. A Safe v1.4.1 transaction guard doesn't see module
/// transactions, so MultiChainSig calls `checkModuleTransaction` and `checkAfterModuleExecution` itself. It
/// has already had the Safe verify the signatures, and hands over the Frax approval it verified for rule 1.
///
/// Known limits:
/// - In Safe v1.4.1, module transactions skip the transaction guard. That is deliberate for the
/// RecoveryModule, and MultiChainSig calls the guard itself. Enabling any module is a call to the Safe
/// itself, so rule 3 puts it behind the timelock, and `initialize` refuses a Safe with any module other
/// than those two.
/// - Signed messages (EIP-1271) never pass through this guard, so rules 4 and 5 don't apply to them: a
/// Permit2 permit, an EIP-3009 authorization (USDC) or an off-chain order can move funds directly.
/// FraxFallbackHandler therefore accepts messages only from a Safe that turned on `messagesEnabled`, and
/// turning it on is a loosening that must be scheduled.
/// - Rule 5 sees token balances only. It does not see debt taken against a position the Safe holds, or
/// allowances that are spent in a later transaction. If a capped token's balance can't be read before the
/// transaction (no code on this chain, or balanceOf fails), that token is skipped rather than blocking the
/// whole Safe. If it could be read before but not after, the transaction reverts.
/// - Rule 4 checks only new approve, increaseAllowance and Permit2 approve calls. It doesn't revoke
/// allowances granted before a cap existed or before a spender was removed, and it doesn't recognise
/// other approval functions (approveAndCall, a token's own multicall, ...).
contract FraxGuard is ITransactionGuard {
// ---------------------------------------------------------------------------------------------------------
// Constants and immutables
// ---------------------------------------------------------------------------------------------------------
/// @notice Cap key for the chain's native asset.
address public constant NATIVE_TOKEN = address(0);
/// @notice Canonical Permit2, same address on every chain.
address public constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @notice A cap's allowance refills by `limit` over this period.
uint256 public constant CAP_PERIOD = 1 days;
uint32 public constant MIN_CONFIG_DELAY = 1 days;
uint32 public constant MAX_CONFIG_DELAY = 30 days;
/// @notice A scheduled operation expires this long after the time it first became ready.
uint256 public constant OPERATION_GRACE_PERIOD = 30 days;
uint256 public constant MAX_CAPPED_TOKENS = 16;
/// @notice Gas forwarded to a capped token's balanceOf.
uint256 public constant BALANCE_QUERY_GAS = 100_000;
bytes4 internal constant APPROVE_SELECTOR = 0x095ea7b3; // approve(address,uint256)
bytes4 internal constant INCREASE_ALLOWANCE_SELECTOR = 0x39509351; // increaseAllowance(address,uint256)
bytes4 internal constant PERMIT2_APPROVE_SELECTOR = 0x87517c45; // approve(address,address,uint160,uint48)
bytes4 internal constant MULTISEND_SELECTOR = 0x8d80ff0a; // multiSend(bytes)
/// @dev Safe v1.4.1 GuardManager: keccak256("guard_manager.guard.address").
uint256 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;
/// @dev Safe v1.4.1 FallbackManager: keccak256("fallback_manager.handler.address").
uint256 internal constant FALLBACK_HANDLER_STORAGE_SLOT =
0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
address internal constant SENTINEL_MODULES = address(0x1);
/// @dev keccak256("1.4.1"), the only Safe version this guard is built for.
bytes32 internal constant SUPPORTED_SAFE_VERSION = keccak256("1.4.1");
bytes32 internal constant EXECUTING_NAMESPACE = keccak256("frax.guard.executing");
bytes32 internal constant SNAPSHOT_NAMESPACE = keccak256("frax.guard.snapshot");
bytes32 internal constant ACCOUNT_NAMESPACE = keccak256("frax.guard.account");
/// @dev Values of the executing flag: in a transaction, and in one that ran a scheduled call to the Safe.
uint256 internal constant EXECUTING = 1;
uint256 internal constant EXECUTING_SCHEDULED_CALL = 2;
address public immutable FRAX_SIGNER;
address public immutable MULTISEND_CALL_ONLY;
address public immutable RECOVERY_MODULE;
address public immutable FRAX_FALLBACK_HANDLER;
/// @notice The only module whose transactions this guard checks, and the only caller of the module hooks.
address public immutable MULTICHAIN_SIG;
/// @dev Self-calls that only restore rule 7, so a Safe that requires the co-signer needs no timelock for them:
/// re-enabling the RecoveryModule and re-installing FraxFallbackHandler. A recovery can leave a Safe
/// without the handler; this lets one normal transaction put it back instead of a second recovery. On any
/// other Safe they are ordinary config changes: there the RecoveryModule's quorum is the full threshold,
/// so enabling it only adds a way around this guard after the recovery delay.
bytes32 internal immutable RESTORE_MODULE_CALL;
bytes32 internal immutable RESTORE_HANDLER_CALL;
// ---------------------------------------------------------------------------------------------------------
// Storage
// ---------------------------------------------------------------------------------------------------------
/// @dev `messagesEnabled` is read by FraxFallbackHandler: whether the Safe accepts EIP-1271 messages.
struct SafeConfig {
bool initialized;
bool cosignerRequired;
bool messagesEnabled;
uint32 configDelay;
bytes32 policyHash;
}
/// @dev Refilling allowance: `available` as of `updatedAt`, growing by `limit` per CAP_PERIOD up to `limit`.
struct Cap {
bool enabled;
uint64 updatedAt;
uint128 limit;
uint128 available;
}
struct Scheduled {
uint64 scheduledAt;
uint64 expiresAt;
}
struct CapConfig {
address token;
uint128 limit;
}
struct InitConfig {
bool cosignerRequired;
bool messagesEnabled;
uint32 configDelay;
bytes32 policyHash;
CapConfig[] caps;
address[] approvedSpenders;
}
/// @notice Bumped whenever a Safe's settings are dropped. All other state is keyed by (safe, generation).
mapping(address safe => uint256) public generation;
mapping(bytes32 account => SafeConfig) internal _configs;
mapping(bytes32 account => mapping(address token => Cap)) internal _caps;
mapping(bytes32 account => address[]) internal _cappedTokens;
mapping(bytes32 account => mapping(address spender => bool)) internal _approvedSpenders;
mapping(bytes32 account => mapping(bytes32 opHash => Scheduled)) internal _scheduled;
// ---------------------------------------------------------------------------------------------------------
// Events and errors
// ---------------------------------------------------------------------------------------------------------
event Initialized(
address indexed safe, bool cosignerRequired, bool messagesEnabled, uint32 configDelay, bytes32 policyHash
);
event ConfigCleared(address indexed safe, uint256 newGeneration);
event CosignerRequiredSet(address indexed safe, bool required);
event MessagesEnabledSet(address indexed safe, bool enabled);
event ConfigDelaySet(address indexed safe, uint32 configDelay);
event PolicyHashSet(address indexed safe, bytes32 policyHash);
event CapSet(address indexed safe, address indexed token, uint128 limit);
event CapRemoved(address indexed safe, address indexed token);
event SpenderApprovalSet(address indexed safe, address indexed spender, bool approved);
/// @dev Carries the full call so owners and independent monitors can see what is queued without trusting
/// the Frax backend.
event OperationScheduled(
address indexed safe, bytes32 indexed opHash, address target, bytes data, uint256 readyAt, uint256 expiresAt
);
event OperationCancelled(address indexed safe, bytes32 indexed opHash);
event OperationExecuted(address indexed safe, bytes32 indexed opHash);
error ZeroAddress();
error InconsistentDeployment();
error NotInitialized();
error AlreadyInitialized();
error ModulesEnabled();
error UnsupportedSafeVersion();
error NestedExecution();
error NotExecuting();
error NotMultiChainSig();
error ScheduledCallFailed();
error BalanceUnreadable(address token);
error CosignerSignatureMissing();
error PolicyHashMismatch(bytes32 signed, bytes32 committed);
error DelegateCallNotAllowed(address target);
error UnsupportedDelegateCall();
error GuardHookCall();
error SpenderNotApproved(address token, address spender);
error CapExceeded(address token, uint256 outflow, uint256 available);
error TooManyCappedTokens();
error CapNotSet(address token);
error CosignerNotOwner();
error RecoveryModuleNotEnabled();
error WrongFallbackHandler();
error ThresholdTooLow();
error InvalidConfigDelay();
error InvalidScheduleTarget();
error AlreadyScheduled(bytes32 opHash);
error OperationNotScheduled(bytes32 opHash);
error OperationNotReady(bytes32 opHash, uint256 readyAt);
error OperationExpired(bytes32 opHash);
// ---------------------------------------------------------------------------------------------------------
// Construction and setup
// ---------------------------------------------------------------------------------------------------------
/// @param fraxSigner The shared FraxSigner owner contract.
/// @param multiSendCallOnly The only allowed delegatecall target.
/// @param recoveryModule The RecoveryModule every hybrid Safe must keep enabled.
/// @param fraxFallbackHandler The fallback handler every hybrid Safe must keep.
/// @param multiChainSig The MultiChainSig module, whose transactions this guard checks through the module hooks.
constructor(
address fraxSigner,
address multiSendCallOnly,
address recoveryModule,
address fraxFallbackHandler,
address multiChainSig
) {
if (
fraxSigner == address(0) || multiSendCallOnly == address(0) || recoveryModule == address(0)
|| fraxFallbackHandler == address(0) || multiChainSig == address(0)
) revert ZeroAddress();
MULTICHAIN_SIG = multiChainSig;
FRAX_SIGNER = fraxSigner;
MULTISEND_CALL_ONLY = multiSendCallOnly;
RECOVERY_MODULE = recoveryModule;
FRAX_FALLBACK_HANDLER = fraxFallbackHandler;
RESTORE_MODULE_CALL = keccak256(abi.encodeCall(ISafe.enableModule, (recoveryModule)));
RESTORE_HANDLER_CALL = keccak256(abi.encodeCall(ISafe.setFallbackHandler, (fraxFallbackHandler)));
// The five contracts must agree, or the modules would count FraxSigner toward the customer quorum and the
// handler would stop requiring it.
if (fraxSigner.code.length == 0) revert InconsistentDeployment();
if (
IFraxDeployment(recoveryModule).FRAX_SIGNER() != fraxSigner
|| IFraxDeployment(recoveryModule).MULTISEND_CALL_ONLY() != multiSendCallOnly
|| IFraxDeployment(fraxFallbackHandler).FRAX_SIGNER() != fraxSigner
|| IFraxDeployment(multiChainSig).FRAX_SIGNER() != fraxSigner
|| IFraxDeployment(multiChainSig).MULTISEND_CALL_ONLY() != multiSendCallOnly
) revert InconsistentDeployment();
}
/// @notice Sets the calling Safe's config. Call it before or in the same transaction as setGuard: from
/// Safe.setup through FraxSafeSetup, or batched as [initialize, setGuard] for an existing Safe. A Safe
/// that installed the guard without initializing can only execute this call.
/// @dev The Safe must be v1.4.1, and may have no module except the RecoveryModule and MultiChainSig, since
/// other module transactions skip every check. A hybrid Safe must already have the RecoveryModule and FraxFallbackHandler in place.
/// If the Safe has a config from an earlier installation that is no longer active, that config is
/// dropped first.
function initialize(InitConfig calldata config) external {
address safe = msg.sender;
bytes32 account = _account(safe);
SafeConfig storage cfg = _configs[account];
if (cfg.initialized) {
if (_currentGuard(safe) == address(this)) revert AlreadyInitialized();
account = _clear(safe);
cfg = _configs[account];
}
_validateConfigDelay(config.configDelay);
if (keccak256(bytes(ISafe(safe).VERSION())) != SUPPORTED_SAFE_VERSION) revert UnsupportedSafeVersion();
// Three distinct modules always include one that isn't allowed.
(address[] memory modules,) = ISafe(safe).getModulesPaginated(SENTINEL_MODULES, 3);
for (uint256 i; i < modules.length; ++i) {
if (modules[i] != RECOVERY_MODULE && modules[i] != MULTICHAIN_SIG) revert ModulesEnabled();
}
cfg.initialized = true;
cfg.cosignerRequired = config.cosignerRequired;
cfg.messagesEnabled = config.messagesEnabled;
cfg.configDelay = config.configDelay;
cfg.policyHash = config.policyHash;
for (uint256 i; i < config.caps.length; ++i) {
_writeCap(safe, account, config.caps[i].token, config.caps[i].limit);
}
for (uint256 i; i < config.approvedSpenders.length; ++i) {
address spender = config.approvedSpenders[i];
if (spender == address(0)) revert ZeroAddress();
_approvedSpenders[account][spender] = true;
emit SpenderApprovalSet(safe, spender, true);
}
_checkOwnershipInvariants(safe, cfg);
emit Initialized(safe, config.cosignerRequired, config.messagesEnabled, config.configDelay, config.policyHash);
}
// ---------------------------------------------------------------------------------------------------------
// Guard hooks
// ---------------------------------------------------------------------------------------------------------
/// @inheritdoc ITransactionGuard
function checkTransaction(
address to,
uint256,
bytes calldata data,
Operation operation,
uint256,
uint256,
uint256,
address,
address payable,
bytes calldata signatures,
address
) external override {
_checkTransaction(msg.sender, to, data, operation, signatures, false);
}
/// @inheritdoc ITransactionGuard
function checkAfterExecution(bytes32, bool success) external override {
_checkAfterExecution(msg.sender, success);
}
/// @notice `checkTransaction` for a MultiChainSig transaction of `safe`. Only MultiChainSig can call it, right
/// before it executes the transaction.
/// @param fraxApproval The FraxApproval payload MultiChainSig had the Safe verify for this transaction, or
/// empty if it executes on owner signatures alone.
function checkModuleTransaction(
address safe,
address to,
bytes calldata data,
Operation operation,
bytes calldata fraxApproval
) external {
if (msg.sender != MULTICHAIN_SIG) revert NotMultiChainSig();
_checkTransaction(safe, to, data, operation, fraxApproval, true);
}
/// @notice `checkAfterExecution` for a MultiChainSig transaction of `safe`, which reverts if its call fails.
function checkAfterModuleExecution(address safe) external {
if (msg.sender != MULTICHAIN_SIG) revert NotMultiChainSig();
_checkAfterExecution(safe, true);
}
function _checkAfterExecution(address safe, bool success) internal {
uint256 executingSlot = _slot(EXECUTING_NAMESPACE, safe);
uint256 executing = _tload(executingSlot);
if (executing == 0) revert NotExecuting();
_tstore(executingSlot, 0);
// With safeTxGas or gasPrice set, the Safe doesn't revert when the call fails. Revert here instead, so a
// failed call doesn't use up its scheduled operation and the owners don't have to wait out the delay again.
if (!success && executing == EXECUTING_SCHEDULED_CALL) revert ScheduledCallFailed();
// Caps apply under the settings the transaction started with, even if it re-initialized the guard.
_enforceCaps(safe, bytes32(_tload(_slot(ACCOUNT_NAMESPACE, safe))));
// The transaction removed or replaced this guard: its settings for this Safe no longer apply.
bytes32 account = _currentGuard(safe) == address(this) ? _account(safe) : _clear(safe);
_checkOwnershipInvariants(safe, _configs[account]);
}
function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
return interfaceId == type(ITransactionGuard).interfaceId || interfaceId == type(IERC165).interfaceId;
}
/// @param signatures The Safe transaction's signatures, or for a module transaction the Frax approval.
function _checkTransaction(
address safe,
address to,
bytes calldata data,
Operation operation,
bytes calldata signatures,
bool viaModule
) internal {
// Safe v1.4.1 has no reentrancy lock on execTransaction. Reject a nested execution of the same Safe, on
// either path, so each transaction has exactly one balance snapshot.
uint256 executingSlot = _slot(EXECUTING_NAMESPACE, safe);
if (_tload(executingSlot) != 0) revert NestedExecution();
_tstore(executingSlot, EXECUTING);
bytes32 account = _account(safe);
_tstore(_slot(ACCOUNT_NAMESPACE, safe), uint256(account));
SafeConfig storage cfg = _configs[account];
if (!cfg.initialized) {
// Installed but not configured: the only way forward is to initialize.
if (
operation != Operation.Call || to != address(this) || data.length < 4
|| bytes4(data[0:4]) != this.initialize.selector
) revert NotInitialized();
_tstore(_slot(SNAPSHOT_NAMESPACE, safe), 0);
return;
}
if (cfg.cosignerRequired) _checkCosigner(safe, cfg.policyHash, signatures, viaModule);
if (operation == Operation.DelegateCall) {
if (to != MULTISEND_CALL_ONLY) revert DelegateCallNotAllowed(to);
_checkMultiSend(safe, account, data);
} else {
_checkCall(safe, account, to, data);
}
_snapshotBalances(safe, account);
}
// ---------------------------------------------------------------------------------------------------------
// Rule 1: co-signer
// ---------------------------------------------------------------------------------------------------------
/// @dev On the module path, `signatures` is the Frax approval itself: MultiChainSig had the Safe verify it.
function _checkCosigner(address safe, bytes32 committedPolicy, bytes calldata signatures, bool viaModule)
internal
view
{
bytes calldata payload = signatures;
if (viaModule) {
if (payload.length == 0) revert CosignerSignatureMissing();
} else {
bool found;
(found, payload) = SafeSignatures.findContractSignature(signatures, ISafe(safe).getThreshold(), FRAX_SIGNER);
if (!found) revert CosignerSignatureMissing();
}
if (committedPolicy != bytes32(0)) {
(bool ok, bytes32 signedPolicy) = FraxApproval.policyHashOf(payload);
if (!ok || signedPolicy != committedPolicy) revert PolicyHashMismatch(signedPolicy, committedPolicy);
}
}
// ---------------------------------------------------------------------------------------------------------
// Rules 2-4: call inspection
// ---------------------------------------------------------------------------------------------------------
/// @dev Parses a MultiSendCallOnly batch exactly as MultiSend lays it out:
/// operation (1) | to (20) | value (32) | dataLength (32) | data (dataLength), repeated.
/// Rejects anything that doesn't parse to exactly the end of the payload, so the guard never approves a
/// batch that MultiSend would read differently.
function _checkMultiSend(address safe, bytes32 account, bytes calldata data) internal {
if (data.length < 4 || bytes4(data[0:4]) != MULTISEND_SELECTOR) revert UnsupportedDelegateCall();
uint256 start = 4 + uint256(bytes32(data[4:36]));
uint256 length = uint256(bytes32(data[start:start + 32]));
bytes calldata txs = data[start + 32:start + 32 + length];
uint256 i;
while (i < txs.length) {
if (uint8(txs[i]) != uint8(Operation.Call)) revert UnsupportedDelegateCall();
address to = address(bytes20(txs[i + 1:i + 21]));
uint256 dataLength = uint256(bytes32(txs[i + 53:i + 85]));
bytes calldata inner = txs[i + 85:i + 85 + dataLength];
// MultiSend v1.4.1 calls address(0) literally, but later versions read it as the Safe itself.
// Treat it as the Safe so this check stays safe across MultiSend versions.
if (to == address(0)) to = safe;
_checkCall(safe, account, to, inner);
i += 85 + dataLength;
}
}
function _checkCall(address safe, bytes32 account, address to, bytes calldata data) internal {
// Rule 3: anything the Safe calls on itself changes its configuration, except restoring rule 7 on a Safe
// that requires the co-signer.
if (to == safe) {
if (data.length == 0) return;
if (_configs[account].cosignerRequired) {
bytes32 callHash = keccak256(data);
if (callHash == RESTORE_MODULE_CALL || callHash == RESTORE_HANDLER_CALL) return;
}
_consume(safe, account, keccak256(abi.encode(safe, data)));
_tstore(_slot(EXECUTING_NAMESPACE, safe), EXECUTING_SCHEDULED_CALL);
return;
}
if (data.length < 4) return;
bytes4 selector = bytes4(data[0:4]);
if (to == address(this)) {
// Settings calls are fine; they enforce their own rules. The hooks are not.
if (selector == this.checkTransaction.selector || selector == this.checkAfterExecution.selector) {
revert GuardHookCall();
}
return;
}
// Rule 4: approvals of capped tokens.
if (selector == APPROVE_SELECTOR || selector == INCREASE_ALLOWANCE_SELECTOR) {
if (!_caps[account][to].enabled) return;
(address spender, uint256 amount) = abi.decode(data[4:], (address, uint256));
if (amount != 0 && !_approvedSpenders[account][spender]) revert SpenderNotApproved(to, spender);
} else if (to == PERMIT2 && selector == PERMIT2_APPROVE_SELECTOR) {
(address token, address spender, uint160 amount,) =
abi.decode(data[4:], (address, address, uint160, uint48));
if (_caps[account][token].enabled && amount != 0 && !_approvedSpenders[account][spender]) {
revert SpenderNotApproved(token, spender);
}
}
}
// ---------------------------------------------------------------------------------------------------------
// Rule 5: outflow caps
// ---------------------------------------------------------------------------------------------------------
/// @dev Transient layout per Safe: [base] = count, [base + 1 + 2i] = token, [base + 2 + 2i] = balance before.
/// Tokens whose balance can't be read are left out.
function _snapshotBalances(address safe, bytes32 account) internal {
address[] storage tokens = _cappedTokens[account];
uint256 base = _slot(SNAPSHOT_NAMESPACE, safe);
uint256 count;
for (uint256 i; i < tokens.length; ++i) {
address token = tokens[i];
(bool ok, uint256 balance) = _tryBalanceOf(token, safe);
if (!ok) continue;
_tstore(base + 1 + 2 * count, uint256(uint160(token)));
_tstore(base + 2 + 2 * count, balance);
++count;
}
_tstore(base, count);
}
/// @dev Runs after execution and after any Safe gas refund, so refunds count as outflow too.
function _enforceCaps(address safe, bytes32 account) internal {
uint256 base = _slot(SNAPSHOT_NAMESPACE, safe);
uint256 n = _tload(base);
if (n == 0) return;
for (uint256 i; i < n; ++i) {
address token = address(uint160(_tload(base + 1 + 2 * i)));
Cap storage cap = _caps[account][token];
// A cap removed during this transaction: that removal was itself timelocked.
if (!cap.enabled) continue;
uint256 balanceBefore = _tload(base + 2 + 2 * i);
(bool ok, uint256 balanceAfter) = _tryBalanceOf(token, safe);
// Readable before but not after: the transaction itself broke balanceOf (a pause, an upgrade), so its
// outflow can't be measured.
if (!ok) revert BalanceUnreadable(token);
if (balanceAfter >= balanceBefore) continue;
uint256 outflow = balanceBefore - balanceAfter;
uint256 available = _availableNow(cap);
if (outflow > available) revert CapExceeded(token, outflow, available);
// forge-lint: disable-next-line(unsafe-typecast) -- available <= cap.limit, which is a uint128
cap.available = uint128(available - outflow);
// forge-lint: disable-next-line(unsafe-typecast) -- timestamps fit uint64
cap.updatedAt = uint64(block.timestamp);
}
_tstore(base, 0);
}
function _availableNow(Cap storage cap) internal view returns (uint256) {
uint256 limit = cap.limit;
uint256 refilled = cap.available + (block.timestamp - cap.updatedAt) * limit / CAP_PERIOD;
return refilled > limit ? limit : refilled;
}
/// @dev Never reverts. Fails for a token without code (e.g. a cap set up for another chain), a reverting or
/// gas-hungry balanceOf, or short return data. Copies at most 32 bytes of return data.
function _tryBalanceOf(address token, address account) internal view returns (bool ok, uint256 amount) {
if (token == NATIVE_TOKEN) return (true, account.balance);
if (token.code.length == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, shl(224, 0x70a08231)) // balanceOf(address)
mstore(add(ptr, 4), account)
let success := staticcall(BALANCE_QUERY_GAS, token, ptr, 36, ptr, 32)
ok := and(success, gt(returndatasize(), 31))
if ok { amount := mload(ptr) }
}
}
// ---------------------------------------------------------------------------------------------------------
// Rules 6-7: ownership invariants
// ---------------------------------------------------------------------------------------------------------
function _checkOwnershipInvariants(address safe, SafeConfig storage cfg) internal view {
bool fraxIsOwner = ISafe(safe).isOwner(FRAX_SIGNER);
if (fraxIsOwner && ISafe(safe).getThreshold() < 2) revert ThresholdTooLow();
if (cfg.cosignerRequired) {
if (!fraxIsOwner) revert CosignerNotOwner();
if (!ISafe(safe).isModuleEnabled(RECOVERY_MODULE)) revert RecoveryModuleNotEnabled();
if (_readAddressSlot(safe, FALLBACK_HANDLER_STORAGE_SLOT) != FRAX_FALLBACK_HANDLER) {
revert WrongFallbackHandler();
}
}
}
// ---------------------------------------------------------------------------------------------------------
// Timelock
// ---------------------------------------------------------------------------------------------------------
/// @notice Queues a call that loosens the Safe's configuration: either a call to the Safe itself, or a
/// loosening call to one of this guard's settings functions. The exact call can run once `configDelay`
/// has passed and before the operation expires, and it still needs the Safe's normal signatures then.
/// An expired operation can be scheduled again.
function schedule(address target, bytes calldata data) external returns (bytes32 opHash) {
address safe = msg.sender;
bytes32 account = _account(safe);
SafeConfig storage cfg = _requireInitialized(account);
if (target != safe && target != address(this)) revert InvalidScheduleTarget();
opHash = hashOperation(target, data);
Scheduled storage op = _scheduled[account][opHash];
if (op.scheduledAt != 0 && block.timestamp <= op.expiresAt) revert AlreadyScheduled(opHash);
uint256 readyAt = block.timestamp + cfg.configDelay;
uint256 expiresAt = readyAt + OPERATION_GRACE_PERIOD;
// forge-lint: disable-next-line(unsafe-typecast) -- timestamps fit uint64
op.scheduledAt = uint64(block.timestamp);
// forge-lint: disable-next-line(unsafe-typecast) -- timestamps fit uint64
op.expiresAt = uint64(expiresAt);
emit OperationScheduled(safe, opHash, target, data, readyAt, expiresAt);
}
function cancel(bytes32 opHash) external {
address safe = msg.sender;
bytes32 account = _account(safe);
_requireInitialized(account);
if (_scheduled[account][opHash].scheduledAt == 0) revert OperationNotScheduled(opHash);
delete _scheduled[account][opHash];
emit OperationCancelled(safe, opHash);
}
function hashOperation(address target, bytes calldata data) public pure returns (bytes32) {
return keccak256(abi.encode(target, data));
}
/// @notice A scheduled operation's timing (all zero if it isn't scheduled). `readyAt` uses the Safe's current
/// delay, so raising the delay also delays operations already queued. `expiresAt` is fixed when the
/// operation is scheduled; if a raised delay pushes `readyAt` past it, the operation must be
/// scheduled again.
function operationOf(address safe, bytes32 opHash)
external
view
returns (uint256 scheduledAt, uint256 readyAt, uint256 expiresAt)
{
bytes32 account = _account(safe);
Scheduled storage op = _scheduled[account][opHash];
if (op.scheduledAt == 0) return (0, 0, 0);
return (op.scheduledAt, uint256(op.scheduledAt) + _configs[account].configDelay, op.expiresAt);
}
function _consume(address safe, bytes32 account, bytes32 opHash) internal {
Scheduled storage op = _scheduled[account][opHash];
if (op.scheduledAt == 0) revert OperationNotScheduled(opHash);
uint256 readyAt = uint256(op.scheduledAt) + _configs[account].configDelay;
if (block.timestamp < readyAt) revert OperationNotReady(opHash, readyAt);
if (block.timestamp > op.expiresAt) revert OperationExpired(opHash);
delete _scheduled[account][opHash];
emit OperationExecuted(safe, opHash);
}
/// @dev For loosening settings calls: the Safe must have scheduled this exact call to this guard.
function _consumeSelf(address safe, bytes32 account) internal {
_consume(safe, account, keccak256(abi.encode(address(this), msg.data)));
}
// ---------------------------------------------------------------------------------------------------------
// Settings (called by the Safe). Tightening is immediate; loosening must be scheduled.
// ---------------------------------------------------------------------------------------------------------
/// @notice Turning the requirement on is immediate. Turning it off must be scheduled.
function setCosignerRequired(bool required) external {
address safe = msg.sender;
bytes32 account = _account(safe);
SafeConfig storage cfg = _requireInitialized(account);
if (!required && cfg.cosignerRequired) _consumeSelf(safe, account);
cfg.cosignerRequired = required;
_checkOwnershipInvariants(safe, cfg);
emit CosignerRequiredSet(safe, required);
}
/// @notice Turning EIP-1271 message signing off is immediate. Turning it on must be scheduled: a signed
/// message can move funds without passing this guard's caps or spender allowlist.
function setMessagesEnabled(bool enabled) external {
address safe = msg.sender;
bytes32 account = _account(safe);
SafeConfig storage cfg = _requireInitialized(account);
if (enabled && !cfg.messagesEnabled) _consumeSelf(safe, account);
cfg.messagesEnabled = enabled;
emit MessagesEnabledSet(safe, enabled);
}
/// @notice Raising the delay is immediate. Lowering it must be scheduled.
function setConfigDelay(uint32 configDelay) external {
address safe = msg.sender;
bytes32 account = _account(safe);
SafeConfig storage cfg = _requireInitialized(account);
_validateConfigDelay(configDelay);
if (configDelay < cfg.configDelay) _consumeSelf(safe, account);
cfg.configDelay = configDelay;
emit ConfigDelaySet(safe, configDelay);
}
/// @notice Any change to the committed policy must be scheduled, so a new policy only binds the co-signer
/// after owners have had the full delay to see it.
function setPolicyHash(bytes32 policyHash) external {
address safe = msg.sender;
bytes32 account = _account(safe);
SafeConfig storage cfg = _requireInitialized(account);
_consumeSelf(safe, account);
cfg.policyHash = policyHash;
emit PolicyHashSet(safe, policyHash);
}
/// @notice Adding a cap or lowering one is immediate. Raising one must be scheduled. A raised cap keeps the
/// currently available amount and refills toward the new limit at the new rate.
function setCap(address token, uint128 limit) external {
address safe = msg.sender;
bytes32 account = _account(safe);
_requireInitialized(account);
Cap storage cap = _caps[account][token];
if (cap.enabled && limit > cap.limit) _consumeSelf(safe, account);
_writeCap(safe, account, token, limit);
}
/// @notice Removing a cap must be scheduled.
function removeCap(address token) external {
address safe = msg.sender;
bytes32 account = _account(safe);
_requireInitialized(account);
if (!_caps[account][token].enabled) revert CapNotSet(token);
_consumeSelf(safe, account);
delete _caps[account][token];
address[] storage tokens = _cappedTokens[account];
for (uint256 i; i < tokens.length; ++i) {
if (tokens[i] == token) {
tokens[i] = tokens[tokens.length - 1];
tokens.pop();
break;
}
}
emit CapRemoved(safe, token);
}
/// @notice Approving a spender must be scheduled. Removing one is immediate. Removing a spender does not
/// revoke allowances it already holds; revoke those with approve(spender, 0).
function setApprovedSpender(address spender, bool approved) external {
address safe = msg.sender;
bytes32 account = _account(safe);
_requireInitialized(account);
if (spender == address(0)) revert ZeroAddress();
if (approved && !_approvedSpenders[account][spender]) _consumeSelf(safe, account);
_approvedSpenders[account][spender] = approved;
emit SpenderApprovalSet(safe, spender, approved);
}
// ---------------------------------------------------------------------------------------------------------
// Views
// ---------------------------------------------------------------------------------------------------------
function configOf(address safe) external view returns (SafeConfig memory) {
return _configs[_account(safe)];
}
function capOf(address safe, address token) external view returns (Cap memory) {
return _caps[_account(safe)][token];
}
function cappedTokens(address safe) external view returns (address[] memory) {
return _cappedTokens[_account(safe)];
}
function isApprovedSpender(address safe, address spender) external view returns (bool) {
return _approvedSpenders[_account(safe)][spender];
}
/// @notice How much of `token` the Safe can send out right now (max uint256 if the token isn't capped).
function availableOutflow(address safe, address token) external view returns (uint256) {
Cap storage cap = _caps[_account(safe)][token];
return cap.enabled ? _availableNow(cap) : type(uint256).max;
}
// ---------------------------------------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------------------------------------
function _account(address safe) internal view returns (bytes32) {
return keccak256(abi.encode(safe, generation[safe]));
}
/// @dev Drops every setting, cap, approved spender and scheduled operation of `safe`.
function _clear(address safe) internal returns (bytes32 account) {
uint256 next = ++generation[safe];
emit ConfigCleared(safe, next);
return _account(safe);
}
function _currentGuard(address safe) internal view returns (address) {
return _readAddressSlot(safe, GUARD_STORAGE_SLOT);
}
function _readAddressSlot(address safe, uint256 slot) internal view returns (address) {
return address(uint160(abi.decode(ISafe(safe).getStorageAt(slot, 1), (uint256))));
}
function _requireInitialized(bytes32 account) internal view returns (SafeConfig storage cfg) {
cfg = _configs[account];
if (!cfg.initialized) revert NotInitialized();
}
function _writeCap(address safe, bytes32 account, address token, uint128 limit) internal {
Cap storage cap = _caps[account][token];
if (!cap.enabled) {
if (_cappedTokens[account].length >= MAX_CAPPED_TOKENS) revert TooManyCappedTokens();
_cappedTokens[account].push(token);
cap.enabled = true;
cap.available = limit;
} else {
uint256 available = _availableNow(cap);
// forge-lint: disable-next-line(unsafe-typecast) -- min of the current available amount and a uint128
cap.available = uint128(available < limit ? available : limit);
}
cap.limit = limit;
// forge-lint: disable-next-line(unsafe-typecast) -- timestamps fit uint64
cap.updatedAt = uint64(block.timestamp);
emit CapSet(safe, token, limit);
}
function _validateConfigDelay(uint32 configDelay) internal pure {
if (configDelay < MIN_CONFIG_DELAY || configDelay > MAX_CONFIG_DELAY) revert InvalidConfigDelay();
}
function _slot(bytes32 namespace, address safe) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(namespace, safe)));
}
function _tload(uint256 slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
function _tstore(uint256 slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
src/interfaces/ISafe.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {Operation} from "./ITransactionGuard.sol";
/// @notice The subset of the Safe v1.4.1 interface the Frax contracts use.
interface ISafe {
function VERSION() external view returns (string memory);
function getThreshold() external view returns (uint256);
function isOwner(address owner) external view returns (bool);
function domainSeparator() external view returns (bytes32);
function signedMessages(bytes32 messageHash) external view returns (uint256);
function checkSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures) external view;
function checkNSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures)
external
view;
function getStorageAt(uint256 offset, uint256 length) external view returns (bytes memory);
function setGuard(address guard) external;
function setFallbackHandler(address handler) external;
function enableModule(address module) external;
function isModuleEnabled(address module) external view returns (bool);
function getModulesPaginated(address start, uint256 pageSize)
external
view
returns (address[] memory array, address next);
function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Operation operation)
external
returns (bool success, bytes memory returnData);
}
src/interfaces/ITransactionGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @dev Same encoding as Safe's Enum.Operation (uint8 in the ABI).
enum Operation {
Call,
DelegateCall
}
/// @notice ABI-compatible with Safe v1.4.1 `Guard` (interface id 0xe6d7a83a).
interface ITransactionGuard is IERC165 {
function checkTransaction(
address to,
uint256 value,
bytes calldata data,
Operation operation,
uint256 safeTxGas,
uint256 baseGas,
uint256 gasPrice,
address gasToken,
address payable refundReceiver,
bytes calldata signatures,
address msgSender
) external;
function checkAfterExecution(bytes32 txHash, bool success) external;
}
src/libraries/FraxApproval.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title FraxApproval
/// @notice The payload FraxSigner expects inside a Safe contract signature (the bytes after the v = 0 slot).
/// @dev Packed layout, 103 bytes:
/// validUntil (uint48) | policyHash (bytes32) | r (bytes32) | s (bytes32) | v (uint8)
/// The co-signer key signs the EIP-712 struct below under FraxSigner's domain:
/// FraxApproval(address safe,bytes32 hash,uint48 validUntil,bytes32 policyHash)
/// `hash` is what the Safe asks FraxSigner to validate: the safeTxHash for a transaction, or the
/// SafeMessage hash for an EIP-1271 message.
library FraxApproval {
uint256 internal constant LENGTH = 103;
bytes32 internal constant TYPEHASH =
keccak256("FraxApproval(address safe,bytes32 hash,uint48 validUntil,bytes32 policyHash)");
function decode(bytes calldata payload)
internal
pure
returns (bool ok, uint48 validUntil, bytes32 policyHash, bytes32 r, bytes32 s, uint8 v)
{
if (payload.length != LENGTH) return (false, 0, 0, 0, 0, 0);
validUntil = uint48(bytes6(payload[0:6]));
policyHash = bytes32(payload[6:38]);
r = bytes32(payload[38:70]);
s = bytes32(payload[70:102]);
v = uint8(payload[102]);
ok = true;
}
function policyHashOf(bytes calldata payload) internal pure returns (bool ok, bytes32 policyHash) {
if (payload.length != LENGTH) return (false, 0);
return (true, bytes32(payload[6:38]));
}
function encode(uint48 validUntil, bytes32 policyHash, bytes32 r, bytes32 s, uint8 v)
internal
pure
returns (bytes memory)
{
return abi.encodePacked(validUntil, policyHash, r, s, v);
}
function structHash(address safe, bytes32 hash, uint48 validUntil, bytes32 policyHash)
internal
pure
returns (bytes32)
{
return keccak256(abi.encode(TYPEHASH, safe, hash, validUntil, policyHash));
}
}
src/libraries/SafeSignatures.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
/// @title SafeSignatures
/// @notice Reads the `signatures` blob of a Safe transaction or message.
/// @dev Shared by FraxGuard (transactions), FraxFallbackHandler (EIP-1271 messages) and RecoveryModule (to keep
/// FraxSigner out of the customer quorum).
library SafeSignatures {
/// @notice Finds a contract signature (v = 0) by `owner` among the first `threshold` signatures.
/// @dev Only the first `threshold` 65-byte slots are verified by the Safe. Anything after them is never
/// checked, and a v = 0 slot merely claims an owner address in `r`. So a signature found here is
/// verified only because the Safe already ran checkNSignatures over these same slots, which called
/// `owner.isValidSignature` for it. Never widen the search beyond `threshold`.
/// @return found Whether such a slot exists.
/// @return payload The contract signature bytes the Safe passed to `owner.isValidSignature`.
function findContractSignature(bytes calldata signatures, uint256 threshold, address owner)
internal
pure
returns (bool found, bytes calldata payload)
{
payload = signatures[0:0];
if (signatures.length < threshold * 65) return (false, payload);
for (uint256 i; i < threshold; ++i) {
uint256 pos = i * 65;
if (uint8(signatures[pos + 64]) != 0) continue;
// Same truncation as the Safe: address(uint160(uint256(r))).
if (address(uint160(uint256(bytes32(signatures[pos:pos + 32])))) != owner) continue;
uint256 offset = uint256(bytes32(signatures[pos + 32:pos + 64]));
if (offset > signatures.length || signatures.length - offset < 32) return (false, payload);
uint256 len = uint256(bytes32(signatures[offset:offset + 32]));
if (len > signatures.length - offset - 32) return (false, payload);
return (true, signatures[offset + 32:offset + 32 + len]);
}
return (false, payload);
}
}
Настройки компилятораПоказать
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@safe-global/safe-contracts/=lib/safe-smart-account/contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"safe-smart-account/=lib/safe-smart-account/"
]
}Исходный код и метаданные: Sourcify.
Исходный код принадлежит авторам контракта.