Verified contractExactMIT
EscrowFactoryV7
Address0x75ec277bf8d9a70ef6097d575d5aafd9a1cbc4ec
- Balance
0 ETH
- Transactions
584
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- paris
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,393,080
- Creation transaction
- 0x4cad84da12…61c13b3060
5 files
- contracts/EscrowFactoryV7.solmain25.52 KB
- contracts/ApproverRegistry.sol8.4 KB
- contracts/ApproverRegistryV2.sol5.58 KB
- contracts/Clones1167.sol1.69 KB
- contracts/FactoryGovernance.sol27.47 KB
contracts/EscrowFactoryV7.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import { FactoryGovernance } from "./FactoryGovernance.sol";
import { Clones1167 } from "./Clones1167.sol";
/// @title IEscrowFactoryV7: the surface SwapEscrowV7 needs from its factory.
interface IEscrowFactoryV7 {
function operator() external view returns (address);
function treasury() external view returns (address);
function refundTimeout() external view returns (uint256);
function creationUnlockAt() external view returns (uint256);
function requireApprovals(
bytes4 action, address token, address target, uint256 amount,
bytes32 dataHash, uint256 nonce, uint256 deadline, bytes[] calldata approvals
) external view;
}
/// @title SwapEscrowV7: SwapEscrowV6 with the Hashlock findings fixed.
/// @notice Changes vs V6, by finding:
/// M-01 / L-06: every fund-moving call carries a signed `maxFee` (right after `amount`, bound into
/// the approval dataHash). After the move, `_settleRemainder` sends min(remainder, maxFee) to the
/// treasury and returns everything above it to `userRefund`, so venue under-consumption, venue
/// refunds, late or duplicate deposits and codeless targets can never turn customer principal
/// into fee. `executeLeg2*` reject a target without code.
/// M-04: `sweep` / `sweepEth` are approval-gated (same shape as the Uniswap venue escrows; the signed
/// amount is the on-chain balance), so the operator alone can no longer move an unsettled balance.
/// L-01 / L-07: `executeLeg2Permit2` removed (no caller, no approver branch).
/// Q-01: the pre-call allowance reset is skipped when the allowance is already zero.
/// Q-02: `executeLeg2Native` requires `amount > 0`: a native leg that carries no value has no reason to
/// exist, and a zero-value call into an arbitrary target is exactly the shape of a token call.
/// Q-11: the user refund leg of `_settleRemainder` is a best-effort low-level call that never
/// reverts the swap (`RefundDeferred` is emitted and the balance stays claimable via `refund*`).
/// Fix review Q-16: `maxFee` is capped at `amount` on every settling call (an approver cannot restore
/// whole-remainder sweeping by signing a huge cap); Permit2 is refused as spender and as target (a signed
/// Permit2 grant would survive the allowance reset); a deferred refund is recorded in `deferredRefund`
/// and excluded from every later fee settlement and sweep, so it stays the customer's until claimed.
/// Fix review Q-23 / Q-32 / Q-35: venue reverts bubble up unchanged (`VenueCallFailed` only when the venue
/// returned no data); zero amounts and empty sweeps revert `ZeroAmount` before an approval is consumed;
/// a refund of nothing emits nothing.
/// Gen-11 (external researcher 0xkonde, 2026-11-05): `sweep` / `sweepEth` take an explicit `amount` that the
/// approvers sign, at most the sweepable balance (balance minus the deferred refund), instead of binding
/// the balance read at execution. A 1-unit donation to the escrow between signing and broadcast used to
/// change that balance, void the signatures (`ApprovalSignerUnknown`) and cost an approver round trip
/// each time, repeatable at will; now exactly `amount` moves and whatever arrived on top stays sweepable
/// for a later, separately signed sweep. `AmountExceedsSweepable` guards the cap before any approval is
/// consumed.
/// Gen-11 (external researcher H. A. Yulian, 2026-11-08): a deferred refund was excluded from fees and sweeps
/// but not from the forward and venue paths, which were sized against the raw balance: a later approved
/// move covering the whole balance could spend the reserved refund as inventory and leave the mapping
/// stale. Every outbound move (`forward`, `forwardNative`, `executeLeg2`, `executeLeg2Native`, the sweeps)
/// is now capped at the available balance (balance minus the deferred refund) before any approval is
/// read, so `balance >= deferredRefund[token]` holds on every contract path.
/// Gen-11 (third audit): L-02 `redirectDeferred` is the approval-gated exit for a deferred refund whose address
/// cannot receive it (the approvers sign the alternative destination, the record is cleared). Q-02 the fee
/// leg of a settlement is best effort: a treasury that cannot receive the asset never blocks the customer,
/// the fee joins the user's refund leg (`FeeWaived`). Q-01 is the inventory cap above.
contract SwapEscrowV7 {
address public immutable factory;
// slot 0: written once by initialize()
address public userRefund;
uint64 private _refundUnlockAt;
bool private _initialized;
uint256 public approvalNonce;
uint256 private _entered; // 0 = free (a fresh clone's storage is all zero)
/// @notice Refund amounts whose best-effort delivery failed, per token (address(0) = native). Never counted
/// as fee, never swept; `refundToUser` / `refundEthToUser` deliver and clear them.
mapping(address => uint256) public deferredRefund;
/// @dev Canonical Permit2 (same address on every chain this generation is deployed on).
address public constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/// @dev Gas given to the best-effort refund leg (user-controlled receiver); the claim paths have no cap.
uint256 private constant REFUND_GAS_NATIVE = 150_000;
uint256 private constant REFUND_GAS_TOKEN = 200_000;
event Forwarded(address indexed token, address indexed dest, uint256 amount);
event ExecutedLeg2(address indexed token, address indexed target, uint256 amount);
event ExecutedLeg2Native(address indexed target, uint256 amount);
event RefundedToUser(address indexed token, uint256 amount);
event RefundDeferred(address indexed token, uint256 amount);
event RefundRedirected(address indexed token, address indexed to, uint256 amount);
event Swept(address indexed token, address indexed treasury, uint256 amount);
event FeeWaived(address indexed token, uint256 amount);
error NotOperator();
error NotFactory();
error AlreadyInitialized();
error RefundLocked();
error ZeroAddress();
error Reentrancy();
error TargetIsToken();
error TargetHasNoCode();
error TokenHasNoCode();
error InsufficientNative();
error InsufficientDeposit();
error ZeroAmount();
error FeeTooLarge();
error PermitTarget();
error VenueCallFailed();
error SentinelAddress();
error AmountExceedsSweepable();
modifier nonReentrant() {
if (_entered == 1) revert Reentrancy();
_entered = 1;
_;
_entered = 0;
}
constructor() {
factory = msg.sender;
_initialized = true;
}
function initialize(address _userRefund) external {
if (msg.sender != factory) revert NotFactory();
if (_initialized) revert AlreadyInitialized();
if (_userRefund == address(0)) revert ZeroAddress();
if (uint160(_userRefund) <= 2) revert SentinelAddress();
_initialized = true;
userRefund = _userRefund;
_refundUnlockAt = uint64(IEscrowFactoryV7(factory).creationUnlockAt());
}
function refundUnlockAt() external view returns (uint256) {
return _refundUnlockAt;
}
function _operator() internal view returns (address) {
return IEscrowFactoryV7(factory).operator();
}
modifier onlyOperator() {
if (msg.sender != _operator()) revert NotOperator();
_;
}
function _approved(
bytes4 action, address token, address target, uint256 amount, bytes32 dataHash,
uint256 deadline, bytes[] calldata approvals
) internal {
IEscrowFactoryV7(factory).requireApprovals(action, token, target, amount, dataHash, approvalNonce, deadline, approvals);
approvalNonce++;
}
// ─── guarded: operator + approvals ────────────────────────────────────────
/// @dev dataHash = keccak256(abi.encode(maxFee)).
function forward(address token, address dest, uint256 amount, uint256 maxFee, uint256 deadline, bytes[] calldata approvals)
external onlyOperator nonReentrant
{
if (dest == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
if (maxFee > amount) revert FeeTooLarge();
if (amount > _sweepable(token, _balanceOf(token))) revert InsufficientDeposit();
_approved(this.forward.selector, token, dest, amount, keccak256(abi.encode(maxFee)), deadline, approvals);
_safeTransfer(token, dest, amount);
emit Forwarded(token, dest, amount);
_settleRemainder(token, maxFee);
}
/// @dev dataHash = keccak256(abi.encode(maxFee)).
function forwardNative(address dest, uint256 amount, uint256 maxFee, uint256 deadline, bytes[] calldata approvals)
external onlyOperator nonReentrant
{
if (dest == address(0)) revert ZeroAddress();
if (amount == 0) revert ZeroAmount();
if (maxFee > amount) revert FeeTooLarge();
if (amount > _sweepable(address(0), address(this).balance)) revert InsufficientNative();
_approved(this.forwardNative.selector, address(0), dest, amount, keccak256(abi.encode(maxFee)), deadline, approvals);
_sendEth(dest, amount);
emit Forwarded(address(0), dest, amount);
_settleNativeRemainder(maxFee);
}
/// @dev dataHash = keccak256(abi.encode(spender, data, maxFee)): the approver signs the exact venue call.
function executeLeg2(
address token, address spender, address target, bytes calldata data, uint256 amount, uint256 maxFee,
uint256 deadline, bytes[] calldata approvals
) external onlyOperator nonReentrant {
if (spender == address(0) || target == address(0)) revert ZeroAddress();
if (target == token) revert TargetIsToken();
if (spender == PERMIT2 || target == PERMIT2) revert PermitTarget();
if (target.code.length == 0) revert TargetHasNoCode();
if (amount == 0) revert ZeroAmount();
if (maxFee > amount) revert FeeTooLarge();
if (amount > _sweepable(token, _balanceOf(token))) revert InsufficientDeposit();
_approved(this.executeLeg2.selector, token, target, amount, keccak256(abi.encode(spender, data, maxFee)), deadline, approvals);
_resetApproveIfNeeded(token, spender);
_safeApprove(token, spender, amount);
(bool ok, bytes memory ret) = target.call(data);
if (!ok) _bubble(ret);
_resetApproveIfNeeded(token, spender); // a full pull leaves 0: nothing to reset (Q-01 token class survives)
emit ExecutedLeg2(token, target, amount);
_settleRemainder(token, maxFee);
}
/// @dev dataHash = keccak256(abi.encode(data, maxFee)). Q-02: value must be > 0 (see the contract notice).
function executeLeg2Native(
address target, bytes calldata data, uint256 amount, uint256 maxFee,
uint256 deadline, bytes[] calldata approvals
) external onlyOperator nonReentrant {
if (target == address(0)) revert ZeroAddress();
if (target == PERMIT2) revert PermitTarget();
if (amount == 0) revert ZeroAmount();
if (maxFee > amount) revert FeeTooLarge();
if (target.code.length == 0) revert TargetHasNoCode();
if (amount > _sweepable(address(0), address(this).balance)) revert InsufficientNative();
_approved(this.executeLeg2Native.selector, address(0), target, amount, keccak256(abi.encode(data, maxFee)), deadline, approvals);
(bool ok, bytes memory ret) = target.call{ value: amount }(data);
if (!ok) _bubble(ret);
emit ExecutedLeg2Native(target, amount);
_settleNativeRemainder(maxFee);
}
/// @notice Fee remainder to the treasury, approval-gated. The approvers sign `amount`; it may not exceed the
/// sweepable balance (on-chain balance minus any deferred refund, which stays the customer's). Anything
/// above `amount` (a donation that landed after signing) stays in the escrow, sweepable later.
function sweep(address token, uint256 amount, uint256 deadline, bytes[] calldata approvals) external onlyOperator nonReentrant {
address t = IEscrowFactoryV7(factory).treasury();
if (amount == 0) revert ZeroAmount();
if (amount > _sweepable(token, _balanceOf(token))) revert AmountExceedsSweepable();
_approved(this.sweep.selector, token, t, amount, bytes32(0), deadline, approvals);
_safeTransfer(token, t, amount);
emit Swept(token, t, amount);
}
function sweepEth(uint256 amount, uint256 deadline, bytes[] calldata approvals) external onlyOperator nonReentrant {
address t = IEscrowFactoryV7(factory).treasury();
if (amount == 0) revert ZeroAmount();
if (amount > _sweepable(address(0), address(this).balance)) revert AmountExceedsSweepable();
_approved(this.sweepEth.selector, address(0), t, amount, bytes32(0), deadline, approvals);
_sendEth(t, amount);
emit Swept(address(0), t, amount);
}
/// @notice L-02: a deferred refund whose address cannot receive it (blocklisted, or a contract that rejects the
/// asset) leaves through here, to a destination the approvers sign; the record is cleared. The amount is
/// the whole record, never more (`token == address(0)` = native).
function redirectDeferred(address token, address to, uint256 deadline, bytes[] calldata approvals) external onlyOperator nonReentrant {
if (to == address(0) || to == address(this)) revert ZeroAddress();
if (uint160(to) <= 2) revert SentinelAddress();
uint256 amount = deferredRefund[token];
if (amount == 0) revert ZeroAmount();
_approved(this.redirectDeferred.selector, token, to, amount, bytes32(0), deadline, approvals);
delete deferredRefund[token];
if (token == address(0)) _sendEth(to, amount); else _safeTransfer(token, to, amount);
emit RefundRedirected(token, to, amount);
}
// ─── unguarded: destinations fixed by the contract ────────────────────────
function refundToUser(address token) external nonReentrant {
if (userRefund == address(0)) revert ZeroAddress(); // the locked implementation itself
if (msg.sender != _operator() && block.timestamp < _refundUnlockAt) revert RefundLocked();
uint256 bal = _balanceOf(token);
delete deferredRefund[token];
if (bal == 0) return;
_safeTransfer(token, userRefund, bal);
emit RefundedToUser(token, bal);
}
function refundEthToUser() external nonReentrant {
if (userRefund == address(0)) revert ZeroAddress();
if (msg.sender != _operator() && block.timestamp < _refundUnlockAt) revert RefundLocked();
uint256 bal = address(this).balance;
delete deferredRefund[address(0)];
if (bal == 0) return;
_sendEth(userRefund, bal);
emit RefundedToUser(address(0), bal);
}
receive() external payable {}
// ─── settlement: capped fee to treasury, excess back to the user ─────────
/// @dev The part of a balance that is not a deferred refund: the most any outbound move may take.
function _sweepable(address token, uint256 bal) internal view returns (uint256) {
uint256 d = deferredRefund[token];
return bal > d ? bal - d : 0;
}
/// @dev min(remainder, maxFee) -> treasury (best effort, Q-02: a failed fee leg joins the user leg instead of
/// blocking the settlement), rest -> userRefund (best effort, Q-11).
function _settleRemainder(address token, uint256 maxFee) internal {
uint256 rem = _sweepable(token, _balanceOf(token));
if (rem == 0) return;
address t = IEscrowFactoryV7(factory).treasury();
uint256 fee = rem > maxFee ? maxFee : rem;
uint256 back = rem - fee;
if (fee > 0) {
if (_tryTransfer(token, t, fee)) emit Swept(token, t, fee);
else { back += fee; emit FeeWaived(token, fee); }
}
if (back > 0) {
if (_tryTransfer(token, userRefund, back)) emit RefundedToUser(token, back);
else { deferredRefund[token] += back; emit RefundDeferred(token, back); }
}
}
function _settleNativeRemainder(uint256 maxFee) internal {
uint256 rem = _sweepable(address(0), address(this).balance);
if (rem == 0) return;
address t = IEscrowFactoryV7(factory).treasury();
uint256 fee = rem > maxFee ? maxFee : rem;
uint256 back = rem - fee;
if (fee > 0) {
if (_trySendEth(t, fee)) emit Swept(address(0), t, fee);
else { back += fee; emit FeeWaived(address(0), fee); }
}
if (back > 0) {
if (_trySendEth(userRefund, back)) emit RefundedToUser(address(0), back);
else { deferredRefund[address(0)] += back; emit RefundDeferred(address(0), back); }
}
}
/// @dev Re-raise the venue's own revert data so the operator sees why a leg failed (fix review Q-23).
function _bubble(bytes memory ret) internal pure {
if (ret.length == 0) revert VenueCallFailed();
assembly ("memory-safe") {
revert(add(ret, 0x20), mload(ret))
}
}
// ─── token helpers ────────────────────────────────────────────────────────
function _safeTransfer(address token, address to, uint256 amount) internal {
if (token.code.length == 0) revert TokenHasNoCode(); // Q-07 parity with SplitEscrowV4
(bool ok, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, amount));
require(ok && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED");
}
function _safeApprove(address token, address spender, uint256 amount) internal {
if (token.code.length == 0) revert TokenHasNoCode();
(bool ok, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, spender, amount));
require(ok && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED");
}
/// @dev Q-01: tokens such as legacy BNB revert on approve(0); skip the reset when nothing is approved.
function _resetApproveIfNeeded(address token, address spender) internal {
(bool ok, bytes memory data) = token.staticcall(abi.encodeWithSelector(0xdd62ed3e, address(this), spender));
if (ok && data.length >= 32 && abi.decode(data, (uint256)) == 0) return;
_safeApprove(token, spender, 0);
}
function _balanceOf(address token) internal view returns (uint256) {
if (token.code.length == 0) revert TokenHasNoCode(); // Q-07 parity: the gen-11 pre-check reads the balance first
(bool ok, bytes memory data) = token.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
require(ok && data.length >= 32, "BALANCE_FAILED");
return abi.decode(data, (uint256));
}
function _sendEth(address to, uint256 amount) internal {
if (amount == 0) return;
(bool ok, ) = payable(to).call{ value: amount }("");
require(ok, "ETH_SEND_FAILED");
}
/// @dev Q-11: never reverts, never copies return data (a hostile receiver cannot grief the settlement), and
/// gets at most REFUND_GAS_NATIVE so it cannot burn the whole transaction either.
function _trySendEth(address to, uint256 amount) internal returns (bool ok) {
uint256 g = REFUND_GAS_NATIVE;
assembly ("memory-safe") {
ok := call(g, to, amount, 0, 0, 0, 0)
}
}
/// @dev Q-11: success = call ok AND (no return data OR first word is non-zero). Return data is read
/// only for its first word; nothing is decoded that could revert. Gas capped at REFUND_GAS_TOKEN.
function _tryTransfer(address token, address to, uint256 amount) internal returns (bool ok) {
bytes memory payload = abi.encodeWithSelector(0xa9059cbb, to, amount);
uint256 g = REFUND_GAS_TOKEN;
assembly ("memory-safe") {
let success := call(g, token, 0, add(payload, 0x20), mload(payload), 0, 0)
let size := returndatasize()
switch success
case 0 { ok := 0 }
default {
switch size
case 0 { ok := iszero(iszero(extcodesize(token))) } // no return data is fine only from real code
default {
switch lt(size, 0x20)
case 1 { ok := 0 } // short return data is not a bool: failure, never a revert
default {
returndatacopy(0, 0, 0x20)
ok := iszero(iszero(mload(0)))
}
}
}
}
}
}
/// @title EscrowFactoryV7: EscrowFactoryV6 with FactoryGovernance (timelocked loosening, immutable
/// timeout, constructor approvers) and the Hashlock fixes.
/// @notice M-05: `predictEscrow` applies the same preconditions as `createEscrow` / `initialize`.
/// Gen-11 (third audit, M-01): `createEscrow` is approval-gated again. The approvers bind the predicted
/// address and `userRefund` at nonce 0, so only the escrow the customer was quoted can ever be deployed and
/// a poisoned refund address never gets its unguarded refund path; anyone may submit the deployment with
/// those approvals (the public recovery listeners hand them out), deploying moves no funds. Q-10: an escrow
/// that already exists is returned instead of reverting, so a front-run creation cannot break a bundled call.
contract EscrowFactoryV7 is FactoryGovernance {
address public immutable implementation;
event EscrowCreated(bytes32 indexed salt, address indexed escrow, address indexed userRefund);
error PredictionMismatch();
error SentinelAddress();
error InvalidRefund();
constructor(
address _owner, address _operator, address _treasury, address _guardian, uint256 _refundTimeout,
address[] memory initialApprovers, uint256 _required, uint256 _minRequired
) FactoryGovernance(_owner, _operator, _treasury, _guardian, _refundTimeout, initialApprovers, _required, _minRequired) {
implementation = address(new SwapEscrowV7());
}
function _eip712Name() internal pure override returns (string memory) { return "InstaswapEscrowFactory"; }
function _eip712Version() internal pure override returns (string memory) { return "11"; }
/// @notice Approval subject: escrow = predictEscrow(salt, userRefund), action = this selector,
/// token 0, target = userRefund, amount 0, dataHash 0, nonce 0.
function createEscrow(bytes32 salt, address userRefund, uint256 deadline, bytes[] calldata approvals)
external returns (address escrow)
{
bytes32 s = _salt(salt, userRefund);
address predicted = Clones1167.predict(implementation, s, address(this));
if (predicted.code.length != 0) return predicted; // Q-10: already deployed (front-run or replay), nothing to do
_validateRefund(userRefund);
_checkApprovals(predicted, this.createEscrow.selector, address(0), userRefund, 0, bytes32(0), 0, deadline, approvals);
escrow = Clones1167.clone(implementation, s);
if (escrow != predicted) revert PredictionMismatch();
SwapEscrowV7(payable(escrow)).initialize(userRefund);
emit EscrowCreated(salt, escrow, userRefund);
}
function predictEscrow(bytes32 salt, address userRefund) external view returns (address) {
_validateRefund(userRefund);
return Clones1167.predict(implementation, _salt(salt, userRefund), address(this));
}
/// @dev Exactly the `initialize` preconditions plus the two contracts a refund can never be meant for, and the
/// loosening cutoff: no address is handed out or deployed in the last CREATION_CUTOFF before a pending
/// approver or operator change executes (LooseningImminent).
function _validateRefund(address userRefund) internal view {
if (userRefund == address(0)) revert ZeroAddress();
if (uint160(userRefund) <= 2) revert SentinelAddress();
if (userRefund == address(this) || userRefund == implementation) revert InvalidRefund();
creationUnlockAt();
}
function _salt(bytes32 salt, address userRefund) internal pure returns (bytes32) {
return keccak256(abi.encode(salt, userRefund));
}
}
contracts/ApproverRegistry.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @title ApproverRegistry: owner-set approver set + EIP-712 M-of-N approval check.
/// @notice Inherited by every V5-generation factory (near-bridge V5, split V2, Uniswap V2/V4V2).
/// An APPROVAL is an EIP-712 signature by an independent policy signer over one specific
/// fund-moving call of one specific escrow:
///
/// Approval(address escrow, bytes4 action, address token, address target,
/// uint256 amount, bytes32 dataHash, uint256 nonce, uint256 deadline)
///
/// The escrow (msg.sender of `requireApprovals`) supplies action/token/target/amount/
/// dataHash from ITS OWN calldata and its own monotonic `approvalNonce`, so a signature
/// can never be replayed on another escrow, another call, another amount or after the
/// escrow's nonce moved. `approvalsRequired` distinct approvers must sign (signatures
/// sorted by ascending signer address). `approvalsRequired == 0` disables the check
/// (staged rollout: deploy -> setApprovers([A],1) -> setApprovers([A,B],2)).
///
/// ESCROW CREATION is guarded too (the factory calls `_checkApprovals` with escrow = the
/// CREATE2 address it is about to deploy, action = its createEscrow selector, target =
/// userRefund, nonce 0): the approver re-derives `predictEscrow(...)` from the parameters
/// the CUSTOMER asked for, so a poisoned deposit address (attacker-chosen userRefund /
/// recipient baked into the escrow) is never deployed and its unguarded refund path never
/// exists. Replay is impossible: the same salt + parameters cannot be deployed twice.
///
/// An approver may never be the operator (`ApproverIsOperator`): the two signatures must
/// come from two different keys on two different machines.
///
/// Verification lives HERE (one copy per factory) and not in the per-swap escrows, so the
/// escrow creation bytecode stays small; escrows read the live set via the factory exactly
/// like they read `operator()`: changing approvers protects in-flight escrows instantly.
abstract contract ApproverRegistry {
bytes32 public constant APPROVAL_TYPEHASH = keccak256(
"Approval(address escrow,bytes4 action,address token,address target,uint256 amount,bytes32 dataHash,uint256 nonce,uint256 deadline)"
);
bytes32 private constant EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
uint256 private constant SECP256K1_HALF_N = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;
address[] internal _approvers;
mapping(address => bool) public isApprover;
uint256 public approvalsRequired;
event ApproversChanged(address[] approvers, uint256 approvalsRequired);
error ApproverZero();
error ApproverDuplicate();
error ApproverIsOperator();
error ThresholdTooHigh();
error ApprovalExpired();
error ApprovalsInsufficient();
error ApprovalBadSignature();
error ApprovalSignerUnknown();
error ApprovalSignersUnsorted();
function approvers() external view returns (address[] memory) {
return _approvers;
}
/// @dev name/version are per-factory (see `_eip712Name`), chainId + this factory bind the domain.
function domainSeparator() public view returns (bytes32) {
return keccak256(abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(_eip712Name())),
keccak256(bytes(_eip712Version())),
block.chainid,
address(this)
));
}
function _eip712Name() internal pure virtual returns (string memory);
function _eip712Version() internal pure virtual returns (string memory);
/// @dev The inheriting factory's current operator (approvers must never equal it).
function _currentOperator() internal view virtual returns (address);
/// @notice The digest an approver signs for a call of `escrow`. Exposed so signers/tests build
/// exactly what the chain verifies. Virtual so a later registry can bind more fields
/// (ApproverRegistryV2 adds the approver epoch); the keyword changes no bytecode here.
function approvalDigest(
address escrow,
bytes4 action,
address token,
address target,
uint256 amount,
bytes32 dataHash,
uint256 nonce,
uint256 deadline
) public view virtual returns (bytes32) {
bytes32 structHash = keccak256(abi.encode(
APPROVAL_TYPEHASH, escrow, action, token, target, amount, dataHash, nonce, deadline
));
return keccak256(abi.encodePacked("\x19\x01", domainSeparator(), structHash));
}
/// @notice Called by an escrow (msg.sender) before a guarded call. Reverts unless
/// `approvalsRequired` distinct approvers signed this exact call. `deadline` is the
/// common expiry the approvers signed; `approvals` are 65-byte r||s||v signatures
/// sorted by ascending signer address.
function requireApprovals(
bytes4 action,
address token,
address target,
uint256 amount,
bytes32 dataHash,
uint256 nonce,
uint256 deadline,
bytes[] calldata approvals
) external view {
_checkApprovals(msg.sender, action, token, target, amount, dataHash, nonce, deadline, approvals);
}
/// @dev Same check with the escrow passed explicitly; the factory uses it for createEscrow
/// (escrow = predicted CREATE2 address).
function _checkApprovals(
address escrow,
bytes4 action,
address token,
address target,
uint256 amount,
bytes32 dataHash,
uint256 nonce,
uint256 deadline,
bytes[] calldata approvals
) internal view virtual {
uint256 need = approvalsRequired;
if (need == 0) return;
if (block.timestamp > deadline) revert ApprovalExpired();
if (approvals.length < need) revert ApprovalsInsufficient();
bytes32 digest = approvalDigest(escrow, action, token, target, amount, dataHash, nonce, deadline);
address last = address(0);
uint256 valid = 0;
for (uint256 i = 0; i < approvals.length; i++) {
address signer = _recover(digest, approvals[i]);
if (signer <= last) revert ApprovalSignersUnsorted(); // also rejects duplicates + zero
if (!isApprover[signer]) revert ApprovalSignerUnknown();
last = signer;
valid++;
}
if (valid < need) revert ApprovalsInsufficient();
}
function _recover(bytes32 digest, bytes calldata sig) internal pure returns (address) {
if (sig.length != 65) revert ApprovalBadSignature();
bytes32 r = bytes32(sig[0:32]);
bytes32 s = bytes32(sig[32:64]);
uint8 v = uint8(sig[64]);
if (v < 27) v += 27;
if (v != 27 && v != 28) revert ApprovalBadSignature();
if (uint256(s) > SECP256K1_HALF_N) revert ApprovalBadSignature(); // low-s only
address signer = ecrecover(digest, v, r, s);
if (signer == address(0)) revert ApprovalBadSignature();
return signer;
}
/// @dev Owner-only in the inheriting factory. Replaces the whole set atomically.
function _setApprovers(address[] calldata newApprovers, uint256 newRequired) internal {
if (newRequired > newApprovers.length) revert ThresholdTooHigh();
address op = _currentOperator();
for (uint256 i = 0; i < _approvers.length; i++) isApprover[_approvers[i]] = false;
delete _approvers;
for (uint256 i = 0; i < newApprovers.length; i++) {
address a = newApprovers[i];
if (a == address(0)) revert ApproverZero();
if (a == op) revert ApproverIsOperator();
if (isApprover[a]) revert ApproverDuplicate();
isApprover[a] = true;
_approvers.push(a);
}
approvalsRequired = newRequired;
emit ApproversChanged(newApprovers, newRequired);
}
}
contracts/ApproverRegistryV2.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import { ApproverRegistry } from "./ApproverRegistry.sol";
/// @title ApproverRegistryV2: ApproverRegistry with the approval deadline always enforced, a ceiling on how far
/// ahead a deadline may lie, the approver epoch bound into every approval, an on-chain build identity,
/// and (gen-10) no gate-off path at all.
/// @notice Hashlock Q-03: in ApproverRegistry, `approvalsRequired == 0` returned before the deadline check, so
/// a factory running with approvals disabled also lost expiry on every guarded call. Here the deadline
/// is checked FIRST, unconditionally, then the signatures.
/// Fix review Q-27 / governance audit Q-03: `deadline` may not lie more than `MAX_APPROVAL_TTL` ahead,
/// so a signer mistake cannot produce an approval that stays valid for years (the signers use 15 min).
/// Governance audit Q-03 (second pass): the signed struct carries `approverEpoch`, a counter the
/// governance layer advances on EVERY change of the approver set or threshold. An approval signed under
/// one set is worthless under the next one, so a bundle that was short of signatures can never become
/// sufficient because a threshold cut executed while it was still inside its deadline.
/// Fix review Q-26: `version()` and ERC-5267 `eip712Domain()` expose the build on-chain, so indexers and
/// signer services can tell factory generations apart without an off-chain address list.
/// Gen-10 (centralisation re-assessment, item 1): the `approvalsRequired == 0` return of the base
/// registry is gone. `_checkApprovals` is implemented here in full: a threshold of zero reverts, every
/// guarded call needs `approvalsRequired` distinct approver signatures, no exception, no gate-off mode.
abstract contract ApproverRegistryV2 is ApproverRegistry {
uint256 public constant MAX_APPROVAL_TTL = 1 hours;
bytes32 public constant APPROVAL_TYPEHASH_V2 = keccak256(
"Approval(address escrow,bytes4 action,address token,address target,uint256 amount,bytes32 dataHash,uint256 nonce,uint256 deadline,uint256 approverEpoch)"
);
/// @notice Advances on every approver set or threshold change (genesis sets it to 1). Signers read it
/// right before signing; the factory binds the live value, so stale approvals fail to recover.
uint256 public approverEpoch;
event ApproverEpochAdvanced(uint256 indexed approverEpoch);
error ApprovalDeadlineTooFar();
error ApprovalsRequiredZero();
/// @notice The EIP-712 version string doubles as the generation tag of this factory build.
function version() external pure returns (string memory) {
return _eip712Version();
}
/// @notice ERC-5267: the domain this factory verifies approvals against.
function eip712Domain()
external view
returns (bytes1 fields, string memory name, string memory ver, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions)
{
return (hex"0f", _eip712Name(), _eip712Version(), block.chainid, address(this), bytes32(0), new uint256[](0));
}
/// @notice Same arguments as the base: the live `approverEpoch` is read from storage, so signers only have
/// to fetch it and put it in the struct they sign.
function approvalDigest(
address escrow,
bytes4 action,
address token,
address target,
uint256 amount,
bytes32 dataHash,
uint256 nonce,
uint256 deadline
) public view override returns (bytes32) {
bytes32 structHash = keccak256(abi.encode(
APPROVAL_TYPEHASH_V2, escrow, action, token, target, amount, dataHash, nonce, deadline, approverEpoch
));
return keccak256(abi.encodePacked("\x19\x01", domainSeparator(), structHash));
}
function _advanceApproverEpoch() internal {
approverEpoch += 1;
emit ApproverEpochAdvanced(approverEpoch);
}
/// @dev Full check, without the base's early return: deadline window first, then `approvalsRequired`
/// distinct known signers in ascending order over the epoch-bound digest.
function _checkApprovals(
address escrow,
bytes4 action,
address token,
address target,
uint256 amount,
bytes32 dataHash,
uint256 nonce,
uint256 deadline,
bytes[] calldata approvals
) internal view virtual override {
if (block.timestamp > deadline) revert ApprovalExpired();
if (deadline > block.timestamp + MAX_APPROVAL_TTL) revert ApprovalDeadlineTooFar();
uint256 need = approvalsRequired;
if (need == 0) revert ApprovalsRequiredZero();
if (approvals.length < need) revert ApprovalsInsufficient();
bytes32 digest = approvalDigest(escrow, action, token, target, amount, dataHash, nonce, deadline);
address last = address(0);
uint256 valid = 0;
for (uint256 i = 0; i < approvals.length; i++) {
address signer = _recover(digest, approvals[i]);
if (signer <= last) revert ApprovalSignersUnsorted(); // also rejects duplicates + zero
if (!isApprover[signer]) revert ApprovalSignerUnknown();
last = signer;
valid++;
}
if (valid < need) revert ApprovalsInsufficient();
}
}
contracts/Clones1167.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @title Clones1167 — deterministic EIP-1167 minimal proxies (CREATE2).
/// @notice A clone is a 45-byte contract that DELEGATECALLs one fixed implementation: it has its own
/// address, balance and storage but runs the implementation's code. Deploying one costs ~45k
/// gas instead of writing the whole escrow bytecode per swap. Plain-Solidity twin of the
/// OpenZeppelin `Clones` library: identical bytecode, and the address formula is reproducible
/// off-chain as keccak256(0xff ++ deployer ++ salt ++ keccak256(initcode(implementation))).
library Clones1167 {
error CloneFailed();
/// @dev 10-byte creation prefix ++ 10-byte runtime prefix ++ implementation ++ 15-byte runtime suffix (55 bytes).
function initcode(address implementation) internal pure returns (bytes memory) {
return abi.encodePacked(
hex"3d602d80600a3d3981f3363d3d373d3d3d363d73",
implementation,
hex"5af43d82803e903d91602b57fd5bf3"
);
}
function predict(address implementation, bytes32 salt, address deployer) internal pure returns (address) {
return address(uint160(uint256(keccak256(abi.encodePacked(hex"ff", deployer, salt, keccak256(initcode(implementation)))))));
}
function clone(address implementation, bytes32 salt) internal returns (address instance) {
bytes memory code = initcode(implementation);
assembly ("memory-safe") {
instance := create2(0, add(code, 0x20), mload(code), salt)
}
if (instance == address(0)) revert CloneFailed();
}
}
contracts/FactoryGovernance.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import { ApproverRegistryV2 } from "./ApproverRegistryV2.sol";
/// @title FactoryGovernance: the owner / operator / treasury / guardian block shared by every approver-gated
/// factory of this generation, with a timelock on every change that LOOSENS security.
/// @notice One copy for the four factory families (near-bridge V7, split V4, Uniswap V4, UniswapV4 V4). Rules:
///
/// ROLES: `owner` decides, `operator` moves funds only with approvals, `treasury` receives fees,
/// `guardian` can only STOP things (cancel a pending change, pause the gate) and never loosen anything.
/// The five roles are pairwise distinct where it matters: owner / operator / treasury are three keys,
/// the guardian is none of owner, operator, treasury or an approver (current or pending), approvers are
/// none of owner, operator, treasury, guardian (governance audit L-02, fix review Q-43, gen-11 Q-08).
/// A key that is both owner and approver, treasury and approver, or guardian and approver, would collapse
/// the separation the approval gate is built on.
///
/// GEN-10 (centralisation re-assessment, items 1 and 2):
/// - `minApprovalsRequired` is an immutable floor under the threshold. Genesis, `scheduleApprovers`
/// and `executeApprovers` all reject a threshold below it, so the owner can never schedule the gate
/// down or off; the registry has no `approvalsRequired == 0` path left (ApproverRegistryV2). The floor
/// itself is at least `ABSOLUTE_MIN_APPROVALS` (2): a single key is never enough to move funds.
/// - `treasury` is immutable. There is no schedule, cancel or execute for it; the only way to a new
/// fee address is a new factory generation. Fees from every escrow of this factory land there and
/// nowhere else.
///
/// INSTANT (tightening or incident response; a captured owner key gains nothing from them):
/// - `raiseThreshold(n)`, `removeApprover(a)`: both DROP a pending approver schedule, so an old
/// snapshot can never put a removed key back or lower a raised threshold (governance audit M-01).
/// Removing a key below the threshold pauses the gate instead of reverting, so a leaked key can
/// always be cut immediately (governance audit L-03). Both advance `approverEpoch`.
/// - `pause()`: owner or guardian; every approval-gated call of a DEPLOYED escrow reverts `GatePaused()`.
/// Creation stays open while paused (it moves no funds and is the only way a counterfactual deposit
/// reaches its refund path) as long as the live approver set can still sign it; after a removal that
/// left the threshold unreachable it waits for the new set like everything else. Refunds are never
/// gated. `unpause()` is the owner's, once the live set can meet the threshold again.
///
/// GEN-11 (third audit, M-01): `createEscrow` is approval-gated again on every factory. The approvers
/// bind the predicted address and `userRefund` (the address commits to every parameter) before the
/// unguarded refund path can exist, so a poisoned quote (attacker-chosen refund address or recipient)
/// is never deployed. Third parties still deploy with approvals obtained from the public recovery
/// listeners, as in gen-9; an escrow that already exists is returned instead of reverting (Q-10).
/// Q-03: an owner nominee may not sit in the pending approver set. Q-08: the guardian is never an approver
/// or the treasury, an approver is never the guardian. Q-09: `cancelGuardian` is the owner's alone, so a
/// guardian can no longer veto its own replacement (a leaked guardian key is replaced after the 48 h delay
/// instead of holding the factory hostage); every other cancel stays owner-or-guardian.
///
/// DELAYED by `GOVERNANCE_DELAY` (48 h), announced on-chain, cancellable by the owner OR the guardian
/// (the guardian change by the owner alone, Q-09), executable by anyone once due and only inside
/// `EXECUTION_WINDOW` after that (a forgotten change lapses instead of staying live forever, governance
/// audit L-04):
/// - `scheduleApprovers(set, required)`: adding or replacing approvers, lowering the threshold down to
/// the floor. Executing advances `approverEpoch`.
/// - `scheduleOperator(o)`: EVERY operator change (governance audit M-02, second pass: an instant
/// rotation let a captured owner key install its operator first and schedule its approvers after,
/// so the order of the two calls decided whether the "loosening pending" guard applied). The new
/// operator may not be any other role, pending ones included (Q-01); the incident response for a
/// leaked operator key is `pause()` plus the schedule.
/// - `scheduleGuardian(g)`: the guardian is the brake, so replacing it is a loosening.
/// - `transferOwnership(new)` + `acceptOwnership()`: the new owner can accept only after the delay
/// and only inside the window, the transfer can be cancelled meanwhile, and accepting clears every
/// pending change of the previous owner (governance audit M-02 and L-04, Q-02).
///
/// WHY THE DELAY PROTECTS DEPOSITS (governance audit M-02): `refundTimeout` is capped at
/// `GOVERNANCE_DELAY - 1 hours`, so every escrow deposited BEFORE a loosening is scheduled unlocks its
/// permissionless refund before the loosening can execute. Escrows created WHILE an approver or
/// operator change is pending (second pass) get `creationUnlockAt()`: their refund unlocks no later
/// than `UNLOCK_MARGIN` before the change can execute, and in the last `CREATION_CUTOFF` before it no
/// escrow can be created or predicted at all (`LooseningImminent`), so no deployed escrow can ever be
/// locked past the moment a new approver set or operator takes over. The guardian cancel stays as the
/// brake for the one case the chain cannot cover: funds sent to an address that was never deployed.
/// A captured owner cannot remove that brake quickly: the guardian only changes through the delayed
/// path, announced 48 h ahead on-chain, and an approver or operator change scheduled after it waits
/// another 48 h, all of it visible to the public watcher.
///
/// IMMUTABLE: `refundTimeout`, `treasury` and `minApprovalsRequired` are constructor arguments without
/// a setter. A quoted deposit address can only ever be deployed with the timeout the customer was quoted.
///
/// GENESIS: the initial approver set and threshold are constructor arguments and the threshold must
/// be at least the floor, so approvals are on from block 1. The initial owner, operator, treasury and
/// guardian are announced in events so monitoring can rebuild the state from the first block.
abstract contract FactoryGovernance is ApproverRegistryV2 {
address public owner;
address public pendingOwner;
uint64 public ownershipEffectiveAt; // 0 = no transfer pending
address public operator;
address public immutable treasury;
address public guardian;
bool public paused;
uint256 public immutable refundTimeout;
/// @notice The threshold can never be scheduled below this (gen-10, item 1). At least ABSOLUTE_MIN_APPROVALS.
uint256 public immutable minApprovalsRequired;
uint256 public constant GOVERNANCE_DELAY = 48 hours;
uint256 public constant EXECUTION_WINDOW = 7 days;
uint256 public constant MIN_REFUND_TIMEOUT = 1 hours;
uint256 public constant MAX_REFUND_TIMEOUT = GOVERNANCE_DELAY - 1 hours;
uint256 public constant MAX_APPROVERS = 16;
/// @notice Lowest floor a factory can be built with: one signature alone never moves funds.
uint256 public constant ABSOLUTE_MIN_APPROVALS = 2;
/// @notice An escrow created while a loosening is pending unlocks at least this long before it executes.
uint256 public constant UNLOCK_MARGIN = 1 hours;
/// @notice No escrow is created or predicted when a loosening executes sooner than this.
uint256 public constant CREATION_CUTOFF = MIN_REFUND_TIMEOUT + UNLOCK_MARGIN;
struct PendingApprovers {
address[] approvers;
uint256 required;
uint64 effectiveAt; // 0 = nothing pending
}
struct PendingOperator {
address operator;
uint64 effectiveAt;
}
struct PendingGuardian {
address guardian;
uint64 effectiveAt;
}
PendingApprovers internal _pendingApprovers;
PendingOperator public pendingOperator;
PendingGuardian public pendingGuardian;
event OperatorChanged(address indexed oldOperator, address indexed newOperator);
event OperatorScheduled(address indexed operator, uint256 effectiveAt);
event OperatorCancelled();
event TreasuryChanged(address indexed oldTreasury, address indexed newTreasury);
event GuardianChanged(address indexed oldGuardian, address indexed newGuardian);
event OwnershipTransferStarted(address indexed currentOwner, address indexed pendingOwner, uint256 effectiveAt);
event OwnershipTransferCancelled(address indexed pendingOwner);
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
event ApproversScheduled(address[] approvers, uint256 approvalsRequired, uint256 effectiveAt);
event ApproversCancelled();
event GuardianScheduled(address indexed guardian, uint256 effectiveAt);
event GuardianCancelled();
event Paused(address indexed by);
event Unpaused(address indexed by);
error NotOwner();
error NotOwnerOrGuardian();
error NotOperator();
error NotPendingOwner();
error ZeroAddress();
error TimeoutOutOfRange();
error TreasuryIsOperator();
error TreasuryIsApprover();
error OwnerIsOperator();
error OwnerIsTreasury();
error ApproverIsOwner();
error GuardianConflict();
error NothingPending();
error NotYetEffective();
error ChangeExpired();
error LooseningImminent();
error NotAnApprover();
error ThresholdUnreachable();
error NotATightening();
error ThresholdBelowFloor();
error FloorTooLow();
error TooManyApprovers();
error ApproversUnsorted();
error GatePaused();
error NotPaused();
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
modifier onlyOwnerOrGuardian() {
if (msg.sender != owner && msg.sender != guardian) revert NotOwnerOrGuardian();
_;
}
/// @param initialApprovers initial approver set, strictly ascending (approvals on from block 1)
/// @param _required initial threshold, at least `_minRequired`
/// @param _minRequired the floor under every future threshold, at least ABSOLUTE_MIN_APPROVALS
constructor(
address _owner,
address _operator,
address _treasury,
address _guardian,
uint256 _refundTimeout,
address[] memory initialApprovers,
uint256 _required,
uint256 _minRequired
) {
if (_owner == address(0) || _operator == address(0) || _treasury == address(0) || _guardian == address(0)) revert ZeroAddress();
if (_treasury == _operator) revert TreasuryIsOperator();
if (_owner == _operator) revert OwnerIsOperator();
if (_owner == _treasury) revert OwnerIsTreasury();
if (_guardian == _owner || _guardian == _operator || _guardian == _treasury) revert GuardianConflict();
if (_refundTimeout < MIN_REFUND_TIMEOUT || _refundTimeout > MAX_REFUND_TIMEOUT) revert TimeoutOutOfRange();
if (_minRequired < ABSOLUTE_MIN_APPROVALS) revert FloorTooLow();
owner = _owner;
operator = _operator;
treasury = _treasury;
guardian = _guardian;
refundTimeout = _refundTimeout;
minApprovalsRequired = _minRequired;
emit OwnershipTransferred(address(0), _owner);
emit OperatorChanged(address(0), _operator);
emit TreasuryChanged(address(0), _treasury);
emit GuardianChanged(address(0), _guardian);
_setApproversMemory(initialApprovers, _required);
}
function _currentOperator() internal view override returns (address) { return operator; }
/// @dev The pause sits in front of every approval check of a deployed escrow. Creation targets an address
/// without code and is let through: deploying moves nothing and opens the customer's refund path.
function _checkApprovals(
address escrow,
bytes4 action,
address token,
address target,
uint256 amount,
bytes32 dataHash,
uint256 nonce,
uint256 deadline,
bytes[] calldata approvals
) internal view override {
if (paused && escrow.code.length != 0) revert GatePaused();
super._checkApprovals(escrow, action, token, target, amount, dataHash, nonce, deadline, approvals);
}
// ─── instant: tightening / incident response ─────────────────────────────
/// @notice Raise the threshold on the current set. Lowering goes through `scheduleApprovers`.
function raiseThreshold(uint256 newRequired) external onlyOwner {
if (newRequired <= approvalsRequired) revert NotATightening();
if (newRequired > _approvers.length) revert ThresholdTooHigh();
_dropPendingApprovers();
approvalsRequired = newRequired;
_advanceApproverEpoch();
emit ApproversChanged(_approvers, newRequired);
}
/// @notice Drop one approver immediately. If the remaining set can no longer meet the threshold the gate is
/// paused in the same transaction: nothing moves until the owner schedules a new set and unpauses.
function removeApprover(address a) external onlyOwner {
if (!isApprover[a]) revert NotAnApprover();
_dropPendingApprovers();
isApprover[a] = false;
uint256 n = _approvers.length;
for (uint256 i = 0; i < n; i++) {
if (_approvers[i] == a) {
_approvers[i] = _approvers[n - 1];
_approvers.pop();
break;
}
}
_advanceApproverEpoch();
emit ApproversChanged(_approvers, approvalsRequired);
if (approvalsRequired > n - 1) _pause();
}
/// @notice Stop every approval-gated call of the deployed escrows (forwards, swaps, sweeps). Creation and
/// refunds are unaffected.
function pause() external onlyOwnerOrGuardian {
_pause();
}
function unpause() external onlyOwner {
if (!paused) revert NotPaused();
if (approvalsRequired > _approvers.length) revert ThresholdUnreachable();
paused = false;
emit Unpaused(msg.sender);
}
// ─── delayed: loosening ───────────────────────────────────────────────────
/// @notice Schedule a full replacement of the approver set and threshold (the only way to add or
/// replace approvers, or to lower the threshold, never below `minApprovalsRequired`). Effective
/// after GOVERNANCE_DELAY, executable for EXECUTION_WINDOW after that.
function scheduleApprovers(address[] calldata newApprovers, uint256 newRequired) external onlyOwner {
_validateApprovers(newApprovers, newRequired);
uint64 at = uint64(block.timestamp + GOVERNANCE_DELAY);
delete _pendingApprovers.approvers;
for (uint256 i = 0; i < newApprovers.length; i++) _pendingApprovers.approvers.push(newApprovers[i]);
_pendingApprovers.required = newRequired;
_pendingApprovers.effectiveAt = at;
emit ApproversScheduled(newApprovers, newRequired, at);
}
function cancelApprovers() external onlyOwnerOrGuardian {
if (_pendingApprovers.effectiveAt == 0) revert NothingPending();
delete _pendingApprovers;
emit ApproversCancelled();
}
/// @notice Anyone may execute a due change; the owner decided it 48 h ago and nobody cancelled it.
function executeApprovers() external {
uint64 at = _pendingApprovers.effectiveAt;
if (at == 0) revert NothingPending();
_requireDue(at);
address[] memory set = _pendingApprovers.approvers;
uint256 req = _pendingApprovers.required;
delete _pendingApprovers;
_setApproversMemory(set, req);
}
function pendingApprovers() external view returns (address[] memory approversList, uint256 required, uint256 effectiveAt) {
return (_pendingApprovers.approvers, _pendingApprovers.required, _pendingApprovers.effectiveAt);
}
/// @notice Every operator change waits the delay (governance audit M-02, second pass). Role-checked now and
/// again at execution.
function scheduleOperator(address _operator) external onlyOwner {
_checkOperatorRole(_operator);
uint64 at = uint64(block.timestamp + GOVERNANCE_DELAY);
pendingOperator = PendingOperator({ operator: _operator, effectiveAt: at });
emit OperatorScheduled(_operator, at);
}
function cancelOperator() external onlyOwnerOrGuardian {
if (pendingOperator.effectiveAt == 0) revert NothingPending();
delete pendingOperator;
emit OperatorCancelled();
}
function executeOperator() external {
PendingOperator memory p = pendingOperator;
if (p.effectiveAt == 0) revert NothingPending();
_requireDue(p.effectiveAt);
_checkOperatorRole(p.operator);
delete pendingOperator;
emit OperatorChanged(operator, p.operator);
operator = p.operator;
}
/// @notice When the earliest pending approver or operator change can execute, 0 when none is pending.
/// These two are the changes that decide who can move escrowed funds. A change that is due counts
/// until it is executed or cancelled (anyone may execute it at any moment); a change that has lapsed
/// can never execute and no longer counts.
function looseningEffectiveAt() public view returns (uint256) {
uint256 a = _liveOrZero(_pendingApprovers.effectiveAt);
uint256 o = _liveOrZero(pendingOperator.effectiveAt);
if (a == 0) return o;
if (o == 0) return a;
return a < o ? a : o;
}
function _liveOrZero(uint64 at) internal view returns (uint256) {
if (at == 0 || block.timestamp > uint256(at) + EXECUTION_WINDOW) return 0;
return at;
}
/// @notice The refund unlock an escrow created now receives: `refundTimeout` ahead, capped so that it falls
/// at least `UNLOCK_MARGIN` before any pending loosening can execute. Reverts `LooseningImminent`
/// when that cap would leave less than `MIN_REFUND_TIMEOUT`: no escrow is created, predicted or
/// re-locked (swapHold) in the last `CREATION_CUTOFF` before a loosening runs, nor while a due
/// change waits to be executed.
function creationUnlockAt() public view returns (uint256) {
uint256 unlock = block.timestamp + refundTimeout;
uint256 at = looseningEffectiveAt();
if (at != 0) {
if (at < block.timestamp + CREATION_CUTOFF) revert LooseningImminent();
uint256 cap = at - UNLOCK_MARGIN;
if (cap < unlock) unlock = cap;
}
return unlock;
}
function scheduleGuardian(address _guardian) external onlyOwner {
_checkGuardianRole(_guardian);
uint64 at = uint64(block.timestamp + GOVERNANCE_DELAY);
pendingGuardian = PendingGuardian({ guardian: _guardian, effectiveAt: at });
emit GuardianScheduled(_guardian, at);
}
/// @notice Q-09: only the owner cancels a guardian change, so the guardian cannot block its own replacement.
function cancelGuardian() external onlyOwner {
if (pendingGuardian.effectiveAt == 0) revert NothingPending();
delete pendingGuardian;
emit GuardianCancelled();
}
function executeGuardian() external {
PendingGuardian memory p = pendingGuardian;
if (p.effectiveAt == 0) revert NothingPending();
_requireDue(p.effectiveAt);
_checkGuardianRole(p.guardian);
delete pendingGuardian;
emit GuardianChanged(guardian, p.guardian);
guardian = p.guardian;
}
// ─── ownership (2-step, delayed) ──────────────────────────────────────────
function transferOwnership(address _pendingOwner) external onlyOwner {
if (_pendingOwner == address(0)) revert ZeroAddress();
if (_pendingOwner == operator || _pendingOwner == pendingOperator.operator) revert OwnerIsOperator();
if (_pendingOwner == treasury) revert OwnerIsTreasury();
if (_pendingOwner == guardian || _pendingOwner == pendingGuardian.guardian) revert GuardianConflict();
if (isApprover[_pendingOwner] || _inPendingApprovers(_pendingOwner)) revert ApproverIsOwner();
uint64 at = uint64(block.timestamp + GOVERNANCE_DELAY);
pendingOwner = _pendingOwner;
ownershipEffectiveAt = at;
emit OwnershipTransferStarted(owner, _pendingOwner, at);
}
function cancelOwnershipTransfer() external onlyOwnerOrGuardian {
address p = pendingOwner;
if (p == address(0)) revert NothingPending();
pendingOwner = address(0);
ownershipEffectiveAt = 0;
emit OwnershipTransferCancelled(p);
}
/// @notice The nominee accepts inside the window. Every change queued by the previous owner is dropped.
function acceptOwnership() external {
if (msg.sender != pendingOwner) revert NotPendingOwner();
_requireDue(ownershipEffectiveAt);
_dropPendingApprovers();
if (pendingOperator.effectiveAt != 0) { delete pendingOperator; emit OperatorCancelled(); }
if (pendingGuardian.effectiveAt != 0) { delete pendingGuardian; emit GuardianCancelled(); }
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
pendingOwner = address(0);
ownershipEffectiveAt = 0;
}
// ─── internals ────────────────────────────────────────────────────────────
function _pause() internal {
if (paused) return;
paused = true;
emit Paused(msg.sender);
}
function _dropPendingApprovers() internal {
if (_pendingApprovers.effectiveAt == 0) return;
delete _pendingApprovers;
emit ApproversCancelled();
}
function _requireDue(uint64 at) internal view {
if (block.timestamp < at) revert NotYetEffective();
if (block.timestamp > uint256(at) + EXECUTION_WINDOW) revert ChangeExpired();
}
/// @dev A guardian is none of the other roles, pending ones included (gen-11 Q-08: nor an approver, nor the
/// immutable treasury, which no later governance call could undo).
function _checkGuardianRole(address g) internal view {
if (g == address(0)) revert ZeroAddress();
if (g == owner || g == pendingOwner || g == operator || g == pendingOperator.operator) revert GuardianConflict();
if (g == treasury || isApprover[g] || _inPendingApprovers(g)) revert GuardianConflict();
}
/// @dev An operator is none of the other roles, pending ones included (the treasury is immutable, so a
/// pending treasury no longer exists to check against).
function _checkOperatorRole(address o) internal view {
if (o == address(0)) revert ZeroAddress();
if (o == treasury) revert TreasuryIsOperator();
if (o == owner || o == pendingOwner) revert OwnerIsOperator();
if (o == guardian || o == pendingGuardian.guardian) revert GuardianConflict();
if (isApprover[o] || _inPendingApprovers(o)) revert ApproverIsOperator();
}
function _inPendingApprovers(address a) internal view returns (bool) {
uint256 n = _pendingApprovers.approvers.length;
for (uint256 i = 0; i < n; i++) {
if (_pendingApprovers.approvers[i] == a) return true;
}
return false;
}
/// @dev An approver is none of the other roles, pending ones included.
function _checkApproverRole(address a) internal view {
if (a == address(0)) revert ApproverZero();
if (a == operator || a == pendingOperator.operator) revert ApproverIsOperator();
if (a == owner || a == pendingOwner) revert ApproverIsOwner();
if (a == treasury) revert TreasuryIsApprover();
if (a == guardian || a == pendingGuardian.guardian) revert GuardianConflict();
}
/// @dev Strictly ascending input: duplicates are impossible and the check is linear (fix review Q-42).
/// The threshold must sit between the floor and the set size.
function _validateApprovers(address[] calldata set, uint256 required) internal view {
if (required < minApprovalsRequired) revert ThresholdBelowFloor();
if (required > set.length) revert ThresholdTooHigh();
if (set.length > MAX_APPROVERS) revert TooManyApprovers();
address prev = address(0);
for (uint256 i = 0; i < set.length; i++) {
address a = set[i];
if (a <= prev) revert ApproversUnsorted();
_checkApproverRole(a);
prev = a;
}
}
/// @dev Memory twin of `_validateApprovers` that also writes the set (constructor, executeApprovers).
function _setApproversMemory(address[] memory set, uint256 required) internal {
if (required < minApprovalsRequired) revert ThresholdBelowFloor();
if (required > set.length) revert ThresholdTooHigh();
if (set.length > MAX_APPROVERS) revert TooManyApprovers();
for (uint256 i = 0; i < _approvers.length; i++) isApprover[_approvers[i]] = false;
delete _approvers;
address prev = address(0);
for (uint256 i = 0; i < set.length; i++) {
address a = set[i];
if (a <= prev) revert ApproversUnsorted();
_checkApproverRole(a);
isApprover[a] = true;
_approvers.push(a);
prev = a;
}
approvalsRequired = required;
_advanceApproverEpoch();
emit ApproversChanged(set, required);
}
}
Compiler settingsShow
{
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.