Verified contractPartialUNLICENSED
LiquidationManagerModule
Address0x3b3fa0507cbd2e22694f3fd3486f40743d4bcd24
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- london
- Via IR
- yes
- License
- UNLICENSED
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,335,412
- Creation transaction
- 0xcc5170dcd0…2efff98afe
53 files
The source code is large: one file is shown at a time. Choose a file in the list.
- src/modules/LiquidationManager.solmain62.27 KB
- @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol8.33 KB
- @openzeppelin/contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol4.84 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol9.28 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol6.57 KB
- @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol1.19 KB
- @openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol3.66 KB
- @openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol4.51 KB
- @openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol8.56 KB
- @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol1.15 KB
- @openzeppelin/contracts/access/IAccessControl.sol3.34 KB
- @openzeppelin/contracts/access/extensions/IAccessControlEnumerable.sol1.28 KB
- @openzeppelin/contracts/interfaces/IERC1967.sol637 B
- @openzeppelin/contracts/interfaces/IERC5267.sol740 B
- @openzeppelin/contracts/interfaces/draft-IERC1822.sol882 B
- @openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- @openzeppelin/contracts/proxy/beacon/IBeacon.sol473 B
- @openzeppelin/contracts/utils/Address.sol6 KB
- @openzeppelin/contracts/utils/Arrays.sol20.91 KB
- @openzeppelin/contracts/utils/Comparators.sol443 B
- @openzeppelin/contracts/utils/Errors.sol896 B
- @openzeppelin/contracts/utils/Panic.sol1.97 KB
- @openzeppelin/contracts/utils/SlotDerivation.sol5.32 KB
- @openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
- @openzeppelin/contracts/utils/Strings.sol19.28 KB
- @openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol4.25 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol871 B
- @openzeppelin/contracts/utils/math/Math.sol32.15 KB
- @openzeppelin/contracts/utils/math/SafeCast.sol34.94 KB
- @openzeppelin/contracts/utils/math/SignedMath.sol2.61 KB
- @openzeppelin/contracts/utils/structs/EnumerableSet.sol29.63 KB
- src/interfaces/IAdminModule.sol2.89 KB
- src/interfaces/IBTCSpendAuthorizer.sol10.2 KB
- src/interfaces/ICollateralManager.sol2.82 KB
- src/interfaces/ILITActionValidator.sol4.79 KB
- src/interfaces/ILiquidationManager.sol2.95 KB
- src/interfaces/ILoanOperationsManager.sol7.63 KB
- src/interfaces/IOperationAuthorizationRegistry.sol7.02 KB
- src/interfaces/IPositionManager.sol13.75 KB
- src/interfaces/IPositionManagerCore.sol11.08 KB
- src/interfaces/IUCDController.sol3.5 KB
- src/interfaces/IVersioned.sol215 B
- src/libraries/BitcoinAddressValidator.sol30.13 KB
- src/libraries/ExpiredLoanCalculator.sol3.9 KB
- src/libraries/GlobalNonReentrant.sol1.19 KB
- src/libraries/GlobalReentrancyGuard.sol2.26 KB
- src/libraries/LoanCalculations.sol1.04 KB
- src/libraries/LoanStatus.sol730 B
- src/libraries/MessageHashBuilder.sol1.74 KB
- src/libraries/PositionManagerErrors.sol4.98 KB
- src/libraries/ProtocolConstants.sol4.48 KB
- src/libraries/SafeCalculations.sol15.2 KB
- src/roles/Roles.sol4.76 KB
src/modules/LiquidationManager.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.34;
import "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import "../interfaces/IPositionManagerCore.sol";
import "../interfaces/IUCDController.sol";
import "../interfaces/ILoanOperationsManager.sol";
import "../interfaces/ILITActionValidator.sol";
import "../interfaces/IPositionManager.sol";
import "../interfaces/IOperationAuthorizationRegistry.sol";
import "../interfaces/ILiquidationManager.sol";
import "../libraries/LoanCalculations.sol";
import "../libraries/ExpiredLoanCalculator.sol";
import { LoanStatusLib } from "../libraries/LoanStatus.sol";
import "../libraries/SafeCalculations.sol";
import "../libraries/GlobalNonReentrant.sol";
import "../libraries/ProtocolConstants.sol";
import "../libraries/PositionManagerErrors.sol";
import "../libraries/MessageHashBuilder.sol";
import "../interfaces/IVersioned.sol";
import "../roles/Roles.sol";
/**
* @title LiquidationManagerModule
* @author Diamond Hands Protocol
* @dev Manages position liquidation with upgradeability
* @notice Handles liquidation of undercollateralized positions with UUPS upgrade pattern
* @dev EIP-712 domain and primary types: see `contracts/docs/EIP712_DOMAIN_SPEC.md`.
*/
// Payable surface is OZ UUPS `upgradeToAndCall` only; this module does not custody ETH (aderyn contract-locks-ether).
// aderyn-fp-next-line(contract-locks-ether)
contract LiquidationManagerModule is
Initializable,
AccessControlEnumerableUpgradeable,
ReentrancyGuardUpgradeable,
PausableUpgradeable,
EIP712Upgradeable,
UUPSUpgradeable,
GlobalNonReentrant
{
// ==============================
// Custom errors (gas efficient)
// ==============================
error InvalidPositionId();
error OnlyPositionManager();
error PositionDoesNotExist();
error PositionNotActive();
error AlreadyLiquidated();
error NotLiquidatable();
error ExceedsMaxLiquidation();
// Commit-Reveal System Errors
error AlreadyCommitted();
error CommitAlreadyHeldByOtherLiquidator();
error NoCommitmentFound();
error NotCommitter();
error RevealTooEarly();
error RevealWindowExpired();
/// @notice The reveal attestation was signed before the randomised reveal delay expired (C2).
error StaleRevealQuantum();
error InvalidReveal();
error CommitmentAlreadyExecuted();
error DeadlineExpired();
// MEV Protection Errors
error SameBlockLiquidation();
error CooldownActive();
// Token Operation Errors
error LiquidationBurnFailed();
error NoVersion();
error MissingVERSION();
error EIP712DomainAlreadySet();
/// @dev Mirrors `PositionManager.liquidationPaused()` for liquidator-facing entrypoints on this module.
modifier whenPositionManagerLiquidationsNotPaused() {
if (
positionManager != address(0) &&
IPositionManager(positionManager).liquidationPaused()
) {
revert PositionManagerErrors.LiquidationsPaused();
}
_;
}
// Version tracking
// v1.5.1 (2026-05-17 post-audit): strip the dead admin-liquidation EIP-712 surface
// (`ADMIN_LIQUIDATION_AUTH_TYPEHASH`, `_digestAdminLiquidationAuth`,
// `eip712DigestAdminLiquidation`). The admin-liquidation path was removed on
// 2026-02-21; the typehash and digest view were dead code with no live callers but
// left a functional EIP-712 signing surface. Bytecode shrink, no storage layout change.
// v1.6.0: M-1 — REVEAL_WINDOW shortened 3600s → 600s (shorter liquidation exclusive lock).
// v1.6.2: audit C-2 — bind real vaultAddress into the LiquidationAuthorization EIP-712 digest
// (vault read from trusted core, not caller-supplied).
// v1.6.3: initializeLiquidationEIP712DomainBackfill (reinitializer 4) for a proxy whose
// reinitializer(2) was skipped. No storage layout change.
// v1.6.4: audit C2 — revealAndLiquidate requires the reveal attestation's quantumTimestamp
// to be >= commit.commitTime + requiredDelay (StaleRevealQuantum). Closes reuse of
// the commit-time signature (same digest, same PKP, separate OAR replay lane) and
// of attestations pre-minted at commit time. No digest, CID or storage change.
string public constant VERSION = "1.6.4"; // C2: reveal attestation must post-date the randomised delay
/// @dev EIP-712 primary type — must match lit-actions `liquidation-validator.ts`.
// Audit C-2: `vaultAddress` binds the attestation to the position's real Bitcoin
// vault. The on-chain digest is rebuilt with `position.vaultAddress` from trusted
// core, so a signature attesting a forged/attacker vault fails to verify.
bytes32 private constant LIQUIDATION_AUTHORIZATION_TYPEHASH = keccak256(
"LiquidationAuthorization(bytes32 actionTag,bytes32 positionId,uint256 quantumTimestamp,uint256 btcPrice,uint256 btcVaultBalance,string vaultAddress,address liquidator)"
);
// Role definitions
bytes32 public constant LIQUIDATOR_ROLE = Roles.LIQUIDATOR_ROLE;
bytes32 public constant ADMIN_ROLE = Roles.ADMIN_ROLE;
/// @notice Deprecated as of v1.3.0 — no longer consulted by any function in this contract.
/// Retained on the ABI for backwards-compatibility with off-chain tooling that still reads the constant.
/// Admin functions are now gated by `msg.sender == adminModule` (direct address check); see `onlyAdminModule`.
bytes32 public constant ADMIN_MODULE_ROLE = Roles.ADMIN_MODULE_ROLE;
bytes32 public constant EMERGENCY_PAUSE_ROLE = Roles.EMERGENCY_PAUSE_ROLE;
// Contract dependencies (upgradeable)
IUCDController public ucdController;
ILoanOperationsManager public loanOperationsManager;
ILITActionValidator public litActionValidator;
address public positionManager;
IOperationAuthorizationRegistry public authorizationRegistry;
// H-1 fix: separate reference to the core module for getPositionDetails() calls.
// positionManager is the orchestrating PositionManager (IPositionManager interface);
// positionManagerCore is the PositionManagerCoreModule (IPositionManagerCore interface).
address public positionManagerCore;
// Entropy seeds for randomized commit-reveal delays; populated by _requestVRFRandomness()
// and consumed by _calculateRandomizedDelay(). Source of truth is the LIT-Action-signed
// quantumTimestamp — no Chainlink VRF integration is used or required.
mapping(bytes32 => uint256) public vrfSeeds; // positionId => entropy seed
// Liquidation parameters (upgradeable)
uint256 public liquidationThreshold;
uint256 public maxLiquidationAmount;
uint256 public liquidationTimeout;
// Liquidation tracking
mapping(bytes32 => bool) public liquidatedPositions;
mapping(address => uint256) public liquidationsByLiquidator;
uint256 public totalLiquidations;
uint256 public totalLiquidationVolume;
// ==============================
// Commit-Reveal Liquidation System (Phase 1)
// ==============================
struct LiquidationCommit {
uint256 quantumTimestamp; // Replaces commitHash - serves as commitment identifier and replay protection
uint256 commitTime;
address liquidator;
bool executed;
}
mapping(bytes32 => LiquidationCommit) public liquidationCommits;
// Commit-reveal timing constants with randomization for MEV protection
uint256 public constant MIN_REVEAL_DELAY = 60; // 60 seconds minimum delay
uint256 public constant MAX_RANDOM_DELAY = 240; // Up to 4 minutes additional randomization
// M-1: shortened from 3600s (1h) to 600s (10 min). The valid reveal window is
// [requiredDelay, REVEAL_WINDOW] where requiredDelay <= MIN_REVEAL_DELAY + MAX_RANDOM_DELAY
// (<= 300s), so 600s leaves a comfortable >=300s submission window for the committer while
// cutting the exclusive "no steal until stale" lock — during which no other liquidator can
// take over a committed position — from 60 minutes down to 10. A committer who never reveals
// can now only block others for 10 minutes, bounding the griefing / delayed-liquidation risk.
uint256 public constant REVEAL_WINDOW = 600; // 10 minute execution window
// Default liquidation parameter constants
uint256 public constant DEFAULT_LIQUIDATION_THRESHOLD = 1.1e4; // 110% CR (stored for compatibility)
uint256 public constant DEFAULT_MAX_LIQUIDATION_UCD = 1e6; // 1M UCD cap (× UCD_DECIMALS)
uint256 public constant DEFAULT_LIQUIDATION_TIMEOUT = 24 hours; // 24-hour expiry
// Expired loan escalation parameters
uint256 public constant DEFAULT_EXPIRY_LIQUIDATION_INCREMENT = 50; // 0.5% per day in basis points
// Grace period of 0 matches prior behavior: escalation starts from day 1 of expiry.
// The old ExpiredLoanCalculator.GRACE_PERIOD_DAYS = 30 was a lookup-table size cap
// (threshold jumped to 200% after 30 days), not a pre-escalation grace period.
uint256 public constant DEFAULT_EXPIRED_LOAN_GRACE_PERIOD_DAYS = 0; // no grace period (escalation from day 1)
uint256 public constant DEFAULT_MAX_ESCALATED_THRESHOLD = 2e4; // 200% collateral ratio cap
/// @dev Minimum daily escalation increment (0.1%/day) — escalation must be meaningful.
uint256 public constant MIN_EXPIRY_LIQUIDATION_INCREMENT = 10; // 10 bps
/// @dev Absolute upper bound on the escalated-threshold cap (500% CR). Bounds the value
/// that drives the escalation loop and prevents absurd thresholds.
uint256 public constant MAX_ABS_ESCALATED_THRESHOLD = 5e4; // 50000 bps = 500%
// BTC price sanity bounds — now reads from LoanOperationsManager for consistency (HIGH-4 fix).
// Kept as fallback constants in case loanOperationsManager is not set.
uint256 public constant FALLBACK_MIN_BTC_PRICE = 1e4 * 1e8; // $10,000 floor (8 decimals)
uint256 public constant FALLBACK_MAX_BTC_PRICE = 1e6 * 1e8; // $1,000,000 ceiling (8 decimals)
// ==============================
// MEV Protection System (Phase 2)
// ==============================
/// @dev Per-liquidator MEV-guard state packed into a single 32-byte storage slot.
/// uint64 (8 bytes) + uint64 (8 bytes) = 16 bytes — saves 1 SLOAD + 1 SSTORE
/// per liquidation vs two separate uint256 mappings.
/// uint64 block numbers are safe beyond any realistic EVM future.
/// uint64 timestamps are safe until year 584,942 AD.
struct LiquidatorState {
uint64 lastBlock;
uint64 lastTime;
}
/// @dev Primary storage for MEV-guard state (private; public getters below).
mapping(address => LiquidatorState) private _liquidatorState;
uint256 public constant LIQUIDATION_COOLDOWN = 30; // 30 seconds between liquidations
// Expired loan escalation parameters (admin-configurable)
uint256 public expiryLiquidationIncrementBps;
uint256 public expiredLoanGracePeriodDays;
uint256 public maxEscalatedThreshold;
/// @notice The AdminModule proxy authorised to call admin functions on this contract (v1.3.0+).
address public adminModule;
// Storage gap invariant: used_slots (20) + __gap (30) = 50.
// v1.3.0: appended `adminModule` (1 slot) — decremented __gap by 1.
// See contracts/scripts/shared/verify-gap-invariant.ts and CLAUDE.md "Storage Gap Invariant".
// When adding a storage var, decrement __gap by the number of new slots — do not recompute.
// aderyn-fp-next-line(unused-state-variable)
uint256[30] private __gap;
// -------------------------------------------------------------------------
// Public getters for MEV-guard state (backward-compatible with old mapping API)
// -------------------------------------------------------------------------
/**
* @notice Get the last block number at which a liquidator executed a liquidation.
* @param liquidator Address of the liquidator to query.
* @return uint256 Block number of the most recent liquidation by this address.
*/
function lastLiquidationBlock(address liquidator) external view returns (uint256) {
return _liquidatorState[liquidator].lastBlock;
}
/**
* @notice Get the last Unix timestamp at which a liquidator executed a liquidation.
* @param liquidator Address of the liquidator to query.
* @return uint256 Timestamp of the most recent liquidation by this address.
*/
function lastLiquidationTime(address liquidator) external view returns (uint256) {
return _liquidatorState[liquidator].lastTime;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function _grantRoleOrRevert(bytes32 role, address account) private {
if (!_grantRole(role, account)) revert PositionManagerErrors.UnexpectedRoleGrantFailure();
}
// ==============================
// Modifiers
// ==============================
modifier onlyAdminModule() {
if (msg.sender != adminModule) revert PositionManagerErrors.NotAdminModule();
_;
}
modifier onlyPositionManager() {
if (msg.sender != positionManager) revert OnlyPositionManager();
_;
}
/**
* @dev Anti-MEV protection modifier - prevents same-block liquidations and enforces cooldowns
*/
modifier antiMEVFor(address liquidator) {
// Single SLOAD fetches both lastBlock and lastTime from the packed LiquidatorState slot.
LiquidatorState storage state = _liquidatorState[liquidator];
if (block.number <= state.lastBlock) revert SameBlockLiquidation();
if (block.timestamp < state.lastTime + LIQUIDATION_COOLDOWN) revert CooldownActive();
_;
// Single SSTORE writes both fields back into the same packed slot.
state.lastBlock = uint64(block.number);
state.lastTime = uint64(block.timestamp);
}
function initialize(
address _ucdController,
address _litActionValidator,
address _positionManager,
address _positionManagerCore,
address _admin,
address _loanOperationsManager,
address _adminModule
) external initializer {
__AccessControl_init();
__AccessControlEnumerable_init();
__ReentrancyGuard_init();
__Pausable_init();
__UUPSUpgradeable_init();
__EIP712_init("DiamondHands.Protocol", "1");
_initializeGlobalReentrancyGuard();
if (_ucdController == address(0)) revert PositionManagerErrors.InvalidAddress();
if (_litActionValidator == address(0)) revert PositionManagerErrors.InvalidAddress();
if (_positionManager == address(0)) revert PositionManagerErrors.InvalidAddress();
// M-01: positionManagerCore required at init so fresh deploys never enter
// the bricked-liquidation state where _isPositionLiquidatable would call address(0).
if (_positionManagerCore == address(0)) revert PositionManagerErrors.InvalidAddress();
if (_positionManagerCore.code.length == 0) revert PositionManagerErrors.NotContract();
if (_admin == address(0)) revert PositionManagerErrors.InvalidAddress();
if (_loanOperationsManager == address(0)) revert PositionManagerErrors.InvalidAddress();
if (_loanOperationsManager.code.length == 0) revert PositionManagerErrors.NotContract();
if (_adminModule == address(0)) revert PositionManagerErrors.InvalidAddress();
ucdController = IUCDController(_ucdController);
litActionValidator = ILITActionValidator(_litActionValidator);
positionManager = _positionManager;
positionManagerCore = _positionManagerCore;
loanOperationsManager = ILoanOperationsManager(_loanOperationsManager);
// Module copy kept for ABI / AdminModule views; live math prefers loanOperationsManager with storage fallback
liquidationThreshold = DEFAULT_LIQUIDATION_THRESHOLD;
maxLiquidationAmount = DEFAULT_MAX_LIQUIDATION_UCD * ProtocolConstants.UCD_DECIMALS;
liquidationTimeout = DEFAULT_LIQUIDATION_TIMEOUT;
// Set default expired loan escalation parameters
expiryLiquidationIncrementBps = DEFAULT_EXPIRY_LIQUIDATION_INCREMENT;
expiredLoanGracePeriodDays = DEFAULT_EXPIRED_LOAN_GRACE_PERIOD_DAYS;
maxEscalatedThreshold = DEFAULT_MAX_ESCALATED_THRESHOLD;
_grantRoleOrRevert(DEFAULT_ADMIN_ROLE, _admin);
_grantRoleOrRevert(LIQUIDATOR_ROLE, _admin);
_grantRoleOrRevert(ADMIN_ROLE, _admin);
_grantRoleOrRevert(ADMIN_MODULE_ROLE, _adminModule);
_grantRoleOrRevert(EMERGENCY_PAUSE_ROLE, _admin);
if (_positionManager != _admin) {
_grantRoleOrRevert(EMERGENCY_PAUSE_ROLE, _positionManager);
}
// ADMIN_MODULE_ROLE is deprecated (v1.3.0+); adminModule direct-address check replaces role-based guard.
adminModule = _adminModule;
emit AdminModuleUpdated(address(0), _adminModule);
}
/**
* @notice One-time EIP-712 domain wiring for LiquidationManager proxies deployed before v1.2.0.
* @dev Fresh deploys already call `__EIP712_init` inside `initialize`. Existing upgraded proxies must invoke this once.
* @dev See LoanOperationsManager: do not use `oz-upgrades-validate-as-initializer` on EIP-712-only reinitializers.
*/
function initializeLiquidationEIP712Domain() external reinitializer(2) onlyRole(DEFAULT_ADMIN_ROLE) {
__EIP712_init("DiamondHands.Protocol", "1");
}
/**
* @notice Backfill the EIP-712 domain on a proxy that reached reinitializer(3) without ever
* running reinitializer(2): its domain name/version are empty, so every liquidation
* digest disagrees with the Lit Action's and commit/reveal revert with
* `SignatureVerificationFailed` (Sepolia proxy 0xC4AB…0e76, found 2026-10-20).
* @dev Refuses when the domain is already set (mainnet, fresh deploys), so it never moves a
* healthy proxy's initializer version for nothing.
*/
function initializeLiquidationEIP712DomainBackfill() external reinitializer(4) onlyRole(DEFAULT_ADMIN_ROLE) {
if (bytes(_EIP712Name()).length != 0) revert EIP712DomainAlreadySet();
__EIP712_init("DiamondHands.Protocol", "1");
}
/**
* @notice Wire the AdminModule address for existing proxies upgraded to v1.3.0.
* @dev reinitializer(3): slot 2 is taken by `initializeLiquidationEIP712Domain`.
*/
function initializeAdminModule(address _adminModule) external reinitializer(3) onlyRole(DEFAULT_ADMIN_ROLE) {
if (_adminModule == address(0)) revert PositionManagerErrors.InvalidAddress();
address old = adminModule;
adminModule = _adminModule;
emit AdminModuleUpdated(old, _adminModule);
}
/// @notice Rotate the AdminModule address. Only callable by the current AdminModule (timelock-gated).
function setAdminModule(address newAdminModule) external onlyAdminModule {
if (newAdminModule == address(0)) revert PositionManagerErrors.InvalidAddress();
address old = adminModule;
adminModule = newAdminModule;
emit AdminModuleUpdated(old, newAdminModule);
}
// ==============================
// EIP-712 liquidation digests (verifyingContract = this module proxy)
// ==============================
function _digestLiquidationAuthorization(
bytes32 positionId,
uint256 quantumTimestamp,
uint256 btcPrice,
uint256 btcVaultBalance,
string memory vaultAddress,
address liquidator
) internal view returns (bytes32) {
bytes32 structHash = keccak256(
abi.encode(
LIQUIDATION_AUTHORIZATION_TYPEHASH,
MessageHashBuilder.LIQUIDATION_ACTION_HASH,
positionId,
quantumTimestamp,
btcPrice,
btcVaultBalance,
// EIP-712 encodes a dynamic `string` field as keccak256(bytes(value)).
keccak256(bytes(vaultAddress)),
liquidator
)
);
return _hashTypedDataV4(structHash);
}
/**
* @notice EIP-712 digest for standard liquidation auth (`actionTag` = LIQUIDATION_ACTION_HASH).
* @dev Used by PositionManager commit/reveal and by `isLiquidatable` (same payload fields; one Lit signature).
*/
function eip712DigestLiquidation(
bytes32 positionId,
uint256 quantumTimestamp,
uint256 btcPrice,
uint256 btcVaultBalance,
address liquidator
) external view returns (bytes32) {
// Audit C-2: bind to the position's REAL Bitcoin vault. The vault is read from trusted
// core here (not passed by the caller) so a signature attesting a forged/attacker vault
// cannot verify — and the PositionManager commit/reveal call sites stay byte-for-byte
// unchanged (PositionManager is at the EIP-170 limit). Returns "" for a missing position,
// which still yields a digest no honest validator would have signed.
string memory vaultAddress = IPositionManagerCore(positionManagerCore).getVaultAddress(positionId);
return _digestLiquidationAuthorization(positionId, quantumTimestamp, btcPrice, btcVaultBalance, vaultAddress, liquidator);
}
// ==============================
// Commit-Reveal Liquidation Functions (Phase 1)
// ==============================
/**
* @dev Commit to liquidate a position (Phase 1)
* @param positionId Position identifier to commit for liquidation
* @param quantumTimestamp Quantum timestamp for replay protection and commitment identifier
* @param btcPrice BTC price in USD with 8 decimals (signed by Lit Action)
* @param btcAmountSats BTC vault balance in satoshis (signed by Lit Action)
*/
function commitLiquidation(
bytes32 positionId,
uint256 quantumTimestamp,
uint256 btcPrice,
uint256 btcAmountSats,
address liquidatorAddress
) external nonReentrant onlyPositionManager antiMEVFor(liquidatorAddress) whenNotPaused {
if (positionId == bytes32(0)) revert InvalidPositionId();
if (quantumTimestamp == 0) revert InvalidReveal();
if (liquidatorAddress == address(0)) revert PositionManagerErrors.InvalidAddress();
// M-3 (v1.4.0): bounds + Chainlink BTC/USD cross-check (delegated to LoanOperationsManager).
// Reverts on zero, out-of-bounds, or deviation > priceDeviationToleranceBps.
// audit #3 (v1.6.0): liquidation staleness gate — reverts if the feed is older than maxBtcFeedAgeLiquidation.
loanOperationsManager.validateBtcPrice(btcPrice, ILoanOperationsManager.BtcPricePolicy.Liquidation);
// Check if position already has a pending commit.
// Auto-clear expired or already-executed commits so they cannot permanently
// block future liquidation attempts (CRIT-2 security fix).
// No cross-liquidator takeover while commit is still within REVEAL_WINDOW ("no steal until stale").
{
LiquidationCommit memory existing = liquidationCommits[positionId];
if (existing.commitTime != 0) {
bool isExpiredOrExecuted = existing.executed ||
block.timestamp > existing.commitTime + REVEAL_WINDOW;
if (!isExpiredOrExecuted) {
if (existing.liquidator == liquidatorAddress) revert AlreadyCommitted();
revert CommitAlreadyHeldByOtherLiquidator();
}
delete liquidationCommits[positionId];
}
}
// Verify position is liquidatable at commit time using signed BTC price and vault balance
if (!_isPositionLiquidatable(positionId, btcPrice, btcAmountSats)) revert NotLiquidatable();
// Store commitment with quantumTimestamp (replaces commitHash)
liquidationCommits[positionId] = LiquidationCommit({
quantumTimestamp: quantumTimestamp,
commitTime: block.timestamp,
liquidator: liquidatorAddress,
executed: false
});
// Request VRF randomness for this liquidation.
// quantumTimestamp is LIT-Action-signed — not predictable by block proposers (M-1 fix).
_requestVRFRandomness(positionId, quantumTimestamp);
emit LiquidationCommitted(positionId, liquidatorAddress, quantumTimestamp, block.timestamp);
}
/**
* @dev Reveal commitment and execute liquidation (Phase 2)
* @param positionId Position identifier to liquidate
* @param quantumTimestamp Fresh reveal-time quantum timestamp (distinct from the commit
* quantum); verified and replay-consumed upstream in PositionManager
* @param btcPrice BTC price in USD with 8 decimals (freshly signed by Lit Action at reveal)
* @param btcAmountSats BTC vault balance in satoshis (freshly signed by Lit Action at reveal)
* @param deadline Maximum timestamp for execution (prevents delayed execution)
* @return bool True if liquidation successful
* @notice liquidationValidatorSignature parameter is kept for interface consistency but verification happens upstream
*/
function revealAndLiquidate(
bytes32 positionId,
uint256 quantumTimestamp,
uint256 btcPrice,
uint256 btcAmountSats,
bytes calldata /* liquidationValidatorSignature */,
uint256 deadline,
address liquidatorAddress
) external nonReentrant onlyPositionManager antiMEVFor(liquidatorAddress) whenNotPaused returns (bool) {
if (positionId == bytes32(0)) revert InvalidPositionId();
if (block.timestamp > deadline) revert DeadlineExpired();
if (liquidatorAddress == address(0)) revert PositionManagerErrors.InvalidAddress();
LiquidationCommit memory commit = liquidationCommits[positionId];
// Validate commitment exists
if (commit.commitTime == 0) revert NoCommitmentFound();
if (commit.liquidator != liquidatorAddress) revert NotCommitter();
if (commit.executed) revert CommitmentAlreadyExecuted();
// H-7: the reveal quantum is a FRESH value produced by a second LIT Action signature
// over current market state, and (v1.6.4, audit C2) its freshness is ENFORCED below
// against the randomised delay — not merely assumed. The commitment is bound by
// positionId (mapping key) + commit.liquidator + commit.executed + the timing window
// (the commit quantum is public via LiquidationCommitted, so it was never a hiding
// commitment).
// Check timing constraints with randomized delay. Seed the delay from the STORED commit
// quantum (which seeded vrfSeeds via _requestVRFRandomness) so the liquidator cannot
// grind the fresh reveal quantum to shorten their own delay.
uint256 timeSinceCommit = block.timestamp - commit.commitTime;
uint256 requiredDelay = _calculateRandomizedDelay(positionId, commit.quantumTimestamp);
if (timeSinceCommit < requiredDelay) revert RevealTooEarly();
if (timeSinceCommit > REVEAL_WINDOW) revert RevealWindowExpired();
// C2 (v1.6.4): the reveal attestation must have been minted AFTER the randomised delay
// expired. The Lit Action signs quantumTimestamp = now + QUANTUM_TIMESTAMP_OFFSET (10 s)
// and never a future value, so this proves the attestation post-dates the delay (to
// within 10 s). Without it the commit-time signature (same digest, same PKP, separate
// OAR replay lane) — or a second attestation pre-minted seconds after it — verifies
// again at reveal and the liquidation executes on a stale btcVaultBalance snapshot, the
// exact thing H-7 intended to prevent. Both operands are chain-derived
// (commit.commitTime is the commit block timestamp), so no Lit-clock-vs-chain-clock skew
// can reject an honest reveal.
if (quantumTimestamp < commit.commitTime + requiredDelay) revert StaleRevealQuantum();
// M-3 (v1.4.0): bounds + Chainlink BTC/USD cross-check (delegated to LoanOperationsManager).
// audit #3 (v1.6.0): liquidation staleness gate — reverts if the feed is older than maxBtcFeedAgeLiquidation.
loanOperationsManager.validateBtcPrice(btcPrice, ILoanOperationsManager.BtcPricePolicy.Liquidation);
// Signature verification is done in PositionManager before calling this function
// The liquidationValidatorSignature parameter is kept for interface consistency
// but is not used here since verification happens upstream
// Re-check liquidatability at reveal time using fresh price and vault balance.
// Prevents executing a stale commitment if the borrower repaid or price recovered
// during the commit-reveal window.
// MED-10 fix: fetch position once and pass to both check and execute (saves ~10k gas).
IPositionManagerCore.Position memory position = IPositionManagerCore(positionManagerCore)
.getPositionDetails(positionId);
if (!_isPositionLiquidatableWithData(position, btcPrice, btcAmountSats)) revert NotLiquidatable();
// Mark commitment as executed
liquidationCommits[positionId].executed = true;
// Execute liquidation with cached position data
bool success = _executeLiquidationWithData(position, positionId, btcPrice, btcAmountSats, liquidatorAddress);
emit LiquidationRevealed(positionId, liquidatorAddress, quantumTimestamp, success, block.timestamp);
return success;
}
/**
* @dev Internal function to check if position is liquidatable using signed price and vault balance from Lit Action
* @param positionId Position to check
* @param btcPrice BTC price in USD with 8 decimals (signed by Lit Action)
* @param btcAmountSats BTC vault balance in satoshis (signed by Lit Action)
* @return bool True if liquidatable
*/
/**
* @dev Get the BTC price bounds from LoanOperationsManager (HIGH-4 fix).
* Falls back to hardcoded constants if loanOperationsManager is not set.
*/
/**
* @dev Basis-point threshold for standard (non-expired) liquidation checks.
* Reads LoanOperationsManager when set; otherwise falls back to module storage / default.
*/
function _standardLiquidationThresholdBps() internal view returns (uint256) {
if (address(loanOperationsManager) != address(0)) {
return loanOperationsManager.liquidationThreshold();
}
uint256 stored = liquidationThreshold;
if (stored != 0) {
return stored;
}
return DEFAULT_LIQUIDATION_THRESHOLD;
}
function _isPositionLiquidatable(bytes32 positionId, uint256 btcPrice, uint256 btcAmountSats) internal view returns (bool) {
IPositionManagerCore.Position memory position = IPositionManagerCore(positionManagerCore)
.getPositionDetails(positionId);
return _isPositionLiquidatableWithData(position, btcPrice, btcAmountSats);
}
/// @dev MED-10: accepts pre-fetched position data to avoid duplicate getPositionDetails call.
function _isPositionLiquidatableWithData(
IPositionManagerCore.Position memory position,
uint256 btcPrice,
uint256 btcAmountSats
) internal view returns (bool) {
// M-3 (v1.4.0): bounds + Chainlink BTC/USD cross-check via LOM (returns false instead of
// reverting so a manipulated price cannot grief honest liquidator bots polling this view).
if (address(loanOperationsManager) == address(0)) {
if (btcPrice == 0) return false;
if (btcPrice < FALLBACK_MIN_BTC_PRICE || btcPrice > FALLBACK_MAX_BTC_PRICE) return false;
} else if (!loanOperationsManager.isBtcPriceValid(btcPrice)) {
return false;
}
uint256 cachedDebt = position.ucdDebt;
uint256 cachedExpiryAt = position.expiryAt;
if (position.positionId == bytes32(0)) return false;
if (
position.status != LoanStatusLib.LoanStatus.ACTIVE &&
position.status != LoanStatusLib.LoanStatus.EXPIRED &&
position.status != LoanStatusLib.LoanStatus.LIQUIDATABLE &&
position.status != LoanStatusLib.LoanStatus.LIQUIDATED
) return false;
if (liquidatedPositions[position.positionId]) return false;
SafeCalculations.validateBounds(btcAmountSats, btcPrice, cachedDebt);
uint256 collateralValue = SafeCalculations.safeCollateralValue(btcAmountSats, btcPrice);
bool isExpired = block.timestamp > cachedExpiryAt;
if (isExpired) {
return ExpiredLoanCalculator.isExpiredLoanLiquidatableDynamic(
cachedExpiryAt,
expiryLiquidationIncrementBps,
expiredLoanGracePeriodDays,
maxEscalatedThreshold,
collateralValue,
cachedDebt
);
} else {
uint256 threshold = _standardLiquidationThresholdBps();
return SafeCalculations.isLiquidatable(collateralValue, cachedDebt, threshold);
}
}
/**
* @dev Get current owner of a PKP vault (delegates to LITActionValidator)
* @param pkpId PKP identifier
* @return address Current owner address
*/
function getPkpOwner(bytes32 pkpId) external view returns (address) {
return litActionValidator.pkpOwners(pkpId);
}
/**
* @dev Internal function to execute liquidation
* @param positionId Position to liquidate
* @param btcPrice BTC price in USD with 8 decimals (signed by Lit Action)
* @param btcAmountSats BTC vault balance in satoshis (signed by Lit Action)
* @return bool True if liquidation successful
*/
function _executeLiquidation(
bytes32 positionId,
uint256 btcPrice,
uint256 btcAmountSats,
address liquidator
) internal returns (bool) {
IPositionManagerCore.Position memory position = IPositionManagerCore(positionManagerCore)
.getPositionDetails(positionId);
return _executeLiquidationWithData(position, positionId, btcPrice, btcAmountSats, liquidator);
}
/// @dev MED-10: accepts pre-fetched position data to avoid duplicate getPositionDetails call.
function _executeLiquidationWithData(
IPositionManagerCore.Position memory position,
bytes32 positionId,
uint256 btcPrice,
uint256 btcAmountSats,
address liquidator
) internal returns (bool) {
bytes32 cachedPkpId = position.pkpId;
uint256 cachedDebt = position.ucdDebt;
uint256 cachedExpiryAt = position.expiryAt;
if (position.positionId == bytes32(0)) revert PositionDoesNotExist();
if (!(position.status == LoanStatusLib.LoanStatus.ACTIVE ||
position.status == LoanStatusLib.LoanStatus.EXPIRED ||
position.status == LoanStatusLib.LoanStatus.LIQUIDATABLE ||
position.status == LoanStatusLib.LoanStatus.LIQUIDATED)) {
revert PositionNotActive();
}
if (liquidatedPositions[positionId]) revert AlreadyLiquidated();
// M-04: self-blocking write before any further state changes or external calls,
// so any future refactor that reorders the path cannot reopen a re-entry window.
liquidatedPositions[positionId] = true;
SafeCalculations.validateBounds(btcAmountSats, btcPrice, cachedDebt);
uint256 collateralValue = SafeCalculations.safeCollateralValue(btcAmountSats, btcPrice);
bool positionExpired = block.timestamp > cachedExpiryAt;
bool canLiquidate;
if (positionExpired) {
canLiquidate = ExpiredLoanCalculator.isExpiredLoanLiquidatableDynamic(
cachedExpiryAt,
expiryLiquidationIncrementBps,
expiredLoanGracePeriodDays,
maxEscalatedThreshold,
collateralValue,
cachedDebt
);
} else {
uint256 threshold = _standardLiquidationThresholdBps();
canLiquidate = SafeCalculations.isLiquidatable(collateralValue, cachedDebt, threshold);
}
if (!canLiquidate) revert NotLiquidatable();
// Calculate liquidation parameters.
// This module only supports whole-position liquidation, so debtToRepay is always the
// full cachedDebt. The legacy `maxLiquidationAmount` cap is intentionally NOT enforced
// here: capping a mandatory full-debt burn would let any position whose debt grows past
// the cap (reachable via repeated mints — no aggregate per-position debt ceiling exists)
// become permanently unliquidatable, leaving unbacked UCD as protocol bad debt.
// The storage field is retained for ABI / AdminModule view compatibility only.
uint256 debtToRepay = cachedDebt;
uint256 currentRatio = LoanCalculations.calculateCollateralRatio(collateralValue, cachedDebt);
// EFFECTS: Update remaining state before external calls
// (`liquidatedPositions[positionId] = true` already written above for M-04 self-blocking)
liquidationsByLiquidator[liquidator]++;
totalLiquidations++;
totalLiquidationVolume += debtToRepay;
// INTERACTIONS: External calls after state updates (CEI pattern).
// LOW-3 fix: removed dead manual rollback code from catch block — revert
// already undoes all state changes. Bubble original error for diagnostics.
try ucdController.burnTokens(liquidator, debtToRepay) {
// Burn successful
} catch (bytes memory returnData) {
if (returnData.length > 0) {
assembly ("memory-safe") {
revert(add(returnData, 0x20), mload(returnData))
}
}
revert LiquidationBurnFailed();
}
// Transfer PKP ownership to the liquidator so they can access the BTC vault.
// The liquidator burns UCD (debt repayment) and receives PKP control (BTC access) in return.
// H-2 fix: PKP transfer failure reverts the entire liquidation. Without this, the liquidator
// burns UCD but never receives BTC vault access — a direct loss of funds. The liquidator
// must ensure transferPKPOwnership will succeed before executing the liquidation.
if (cachedPkpId != bytes32(0)) {
litActionValidator.transferPKPOwnership(cachedPkpId, liquidator);
}
// Emit event for position manager to handle state updates
emit PositionLiquidated(
positionId,
liquidator,
currentRatio,
debtToRepay,
collateralValue,
positionExpired,
block.timestamp
);
return true;
}
/**
* @dev Check if position is liquidatable using signed price and vault balance from Lit Action
* @param positionId Position to check
* @param btcPrice BTC price in USD with 8 decimals (signed by Lit Action)
* @param quantumTimestamp Quantum timestamp for replay protection
* @param btcAmountSats BTC vault balance in satoshis (signed by Lit Action)
* @param liquidationValidatorSignature Signature from liquidation Lit Action validator
* @return bool True if position is liquidatable
* @notice Requires LIQUIDATOR_ROLE
*/
function isLiquidatable(
bytes32 positionId,
uint256 quantumTimestamp,
uint256 btcPrice,
uint256 btcAmountSats,
bytes calldata liquidationValidatorSignature
) external view onlyRole(LIQUIDATOR_ROLE) returns (bool) {
if (
positionManager != address(0) &&
IPositionManager(positionManager).liquidationPaused()
) {
return false;
}
// Comprehensive input validation
if (positionId == bytes32(0)) return false;
// M-3 (v1.4.0): bounds + Chainlink BTC/USD cross-check via LOM (returns false for view soft-fail).
if (address(loanOperationsManager) == address(0)) {
if (btcPrice == 0) return false;
if (btcPrice < FALLBACK_MIN_BTC_PRICE || btcPrice > FALLBACK_MAX_BTC_PRICE) return false;
} else if (!loanOperationsManager.isBtcPriceValid(btcPrice)) {
return false;
}
// Audit C-2: fetch the position from trusted core BEFORE building the digest so the
// signed `vaultAddress` is rebuilt from on-chain state — a forged-vault attestation
// cannot verify. Soft-fail to false (this view is for off-chain liquidation polling).
IPositionManagerCore positionManagerContract = IPositionManagerCore(
positionManagerCore
);
IPositionManagerCore.Position memory position = positionManagerContract
.getPositionDetails(positionId);
if (position.positionId == bytes32(0) || liquidatedPositions[positionId]) {
return false;
}
bytes32 messageHash = _digestLiquidationAuthorization(
positionId, quantumTimestamp, btcPrice, btcAmountSats, position.vaultAddress, msg.sender
);
// Verify authorization registry is set
if (address(authorizationRegistry) == address(0)) {
return false;
}
// Verify signature from liquidation Lit Action validator (revert-only → false for this view)
// View-only soft-fail: registry revert does not bubble; returns false for off-chain polling.
try authorizationRegistry.verifyAuthorization(
this.isLiquidatable.selector,
messageHash,
liquidationValidatorSignature
) {} catch {
return false;
}
// Read-only quantum validation — does NOT consume the quantum window (CRIT-1 fix).
// Using isQuantumValid (view) instead of validateQuantum (state-modifying) prevents
// griefing where a caller burns quantum windows to block legitimate liquidations.
if (!authorizationRegistry.isQuantumValidForOperation(positionId, this.isLiquidatable.selector, quantumTimestamp)) {
return false;
}
if (
position.status != LoanStatusLib.LoanStatus.ACTIVE &&
position.status != LoanStatusLib.LoanStatus.EXPIRED &&
position.status != LoanStatusLib.LoanStatus.LIQUIDATABLE
) {
return false;
}
// Use btcAmountSats from Lit Action signature (cryptographically attested vault balance)
SafeCalculations.validateBounds(btcAmountSats, btcPrice, position.ucdDebt);
uint256 collateralValue = SafeCalculations.safeCollateralValue(btcAmountSats, btcPrice);
// Apply escalated threshold for expired positions (consistent with _isPositionLiquidatable)
bool isExpired = block.timestamp > position.expiryAt;
if (isExpired) {
return ExpiredLoanCalculator.isExpiredLoanLiquidatableDynamic(
position.expiryAt,
expiryLiquidationIncrementBps,
expiredLoanGracePeriodDays,
maxEscalatedThreshold,
collateralValue,
position.ucdDebt
);
}
uint256 threshold = _standardLiquidationThresholdBps();
return SafeCalculations.isLiquidatable(collateralValue, position.ucdDebt, threshold);
}
/**
* @notice Get the number of liquidations performed by a specific liquidator.
* @dev Reads from the liquidationsByLiquidator mapping.
* @param liquidator Liquidator address.
* @return uint256 Number of liquidations performed.
*/
function getLiquidatorStats(address liquidator) external view returns (uint256) {
return liquidationsByLiquidator[liquidator];
}
/**
* @notice Get protocol-wide liquidation totals.
* @dev Returns the aggregate count and UCD volume across all liquidations.
* @return liquidationCount Total number of liquidations.
* @return totalVolume Total UCD volume liquidated in wei.
*/
function getGlobalLiquidationStats() external view returns (uint256 liquidationCount, uint256 totalVolume) {
return (totalLiquidations, totalLiquidationVolume);
}
/**
* @dev Update liquidation parameters (admin only)
* @param newLiquidationThreshold New liquidation threshold
* @param newMaxLiquidationAmount New maximum liquidation amount
* @param newLiquidationTimeout New liquidation timeout
*/
function updateLiquidationParameters(
uint256 newLiquidationThreshold,
uint256 newMaxLiquidationAmount,
uint256 newLiquidationTimeout
) external onlyAdminModule {
if (newLiquidationThreshold == 0) revert PositionManagerErrors.InvalidAmount();
if (newMaxLiquidationAmount == 0) revert PositionManagerErrors.InvalidAmount();
if (newLiquidationTimeout == 0) revert PositionManagerErrors.InvalidAmount();
uint256 oldThreshold = liquidationThreshold;
uint256 oldMaxAmount = maxLiquidationAmount;
uint256 oldTimeout = liquidationTimeout;
liquidationThreshold = newLiquidationThreshold;
maxLiquidationAmount = newMaxLiquidationAmount;
liquidationTimeout = newLiquidationTimeout;
emit LiquidationParametersUpdated(
oldThreshold, newLiquidationThreshold,
oldMaxAmount, newMaxLiquidationAmount,
oldTimeout, newLiquidationTimeout,
msg.sender,
block.timestamp
);
}
/**
* @notice Update the daily compound increment applied to expired loan liquidation thresholds.
* @dev Only callable by ADMIN_MODULE_ROLE. Value is in basis points (e.g. 50 = 0.5% per day).
* @param newIncrementBps New daily increment in basis points
* (must be in [MIN_EXPIRY_LIQUIDATION_INCREMENT, BASIS_POINTS]).
*/
function setExpiryLiquidationIncrement(uint256 newIncrementBps) external onlyAdminModule {
// Floor: escalation must be meaningful. Ceiling: 100%/day sanity bound.
if (
newIncrementBps < MIN_EXPIRY_LIQUIDATION_INCREMENT ||
newIncrementBps > ExpiredLoanCalculator.BASIS_POINTS
) revert PositionManagerErrors.InvalidAmount();
uint256 old = expiryLiquidationIncrementBps;
expiryLiquidationIncrementBps = newIncrementBps;
emit ExpiryLiquidationIncrementUpdated(old, newIncrementBps, msg.sender, block.timestamp);
}
/**
* @notice Update the grace period after loan expiry before escalation begins.
* @dev Only callable by ADMIN_MODULE_ROLE. Set to 0 to start escalation immediately on expiry.
* @param newGracePeriodDays Number of days after expiry before increment is applied.
*/
function setExpiredLoanGracePeriod(uint256 newGracePeriodDays) external onlyAdminModule {
uint256 old = expiredLoanGracePeriodDays;
expiredLoanGracePeriodDays = newGracePeriodDays;
emit ExpiredLoanGracePeriodUpdated(old, newGracePeriodDays, msg.sender, block.timestamp);
}
/**
* @notice Update the maximum escalated liquidation threshold for expired loans.
* @dev Only callable by ADMIN_MODULE_ROLE. Must be in
* (BASE_LIQUIDATION_THRESHOLD, MAX_ABS_ESCALATED_THRESHOLD] — i.e. > 11000 bps (110%)
* and <= 50000 bps (500%).
* @param newMaxThreshold New maximum threshold in basis points (e.g. 20000 = 200%).
*/
function setMaxEscalatedThreshold(uint256 newMaxThreshold) external onlyAdminModule {
if (
newMaxThreshold <= ExpiredLoanCalculator.BASE_LIQUIDATION_THRESHOLD ||
newMaxThreshold > MAX_ABS_ESCALATED_THRESHOLD
) revert PositionManagerErrors.InvalidAmount();
uint256 old = maxEscalatedThreshold;
maxEscalatedThreshold = newMaxThreshold;
emit MaxEscalatedThresholdUpdated(old, newMaxThreshold, msg.sender, block.timestamp);
}
/**
* @notice Set the UCDController dependency address.
* @dev Only callable by ADMIN_MODULE_ROLE. New address must be a deployed contract.
* @param newUcdController New UCD controller address.
*/
function setUcdController(
address newUcdController
) external onlyAdminModule {
if (newUcdController == address(0)) revert PositionManagerErrors.InvalidAddress();
if (newUcdController.code.length == 0) revert PositionManagerErrors.NotContract();
address oldUcdController = address(ucdController);
ucdController = IUCDController(newUcdController);
emit UcdControllerUpdated(
oldUcdController, newUcdController,
msg.sender, block.timestamp
);
}
/**
* @notice Update the LoanOperationsManager dependency address.
* @dev Only callable by ADMIN_MODULE_ROLE.
* @param newLoanOps New LoanOperationsManager contract address.
*/
function setLoanOperationsManager(address newLoanOps) external onlyAdminModule {
if (newLoanOps == address(0)) revert PositionManagerErrors.InvalidAddress();
if (newLoanOps.code.length == 0) revert PositionManagerErrors.NotContract();
address oldLoanOps = address(loanOperationsManager);
loanOperationsManager = ILoanOperationsManager(newLoanOps);
emit LoanOperationsManagerUpdated(oldLoanOps, newLoanOps, msg.sender, block.timestamp);
}
/**
* @notice Update the LITActionValidator dependency address.
* @dev Only callable by ADMIN_MODULE_ROLE. Required when redeploying the validator contract.
* @param newLitActionValidator New LITActionValidator contract address.
*/
function setLitActionValidator(address newLitActionValidator) external onlyAdminModule {
if (newLitActionValidator == address(0)) revert PositionManagerErrors.InvalidAddress();
if (newLitActionValidator.code.length == 0) revert PositionManagerErrors.NotContract();
address old = address(litActionValidator);
litActionValidator = ILITActionValidator(newLitActionValidator);
emit LitActionValidatorUpdated(old, newLitActionValidator, msg.sender, block.timestamp);
}
/**
* @notice Set the OperationAuthorizationRegistry used for LIT Action signature verification.
* @dev Only callable by ADMIN_MODULE_ROLE. New address must be a deployed contract.
* @param registry Authorization registry address.
*/
function setAuthorizationRegistry(address registry) external onlyAdminModule {
if (registry == address(0)) revert PositionManagerErrors.InvalidAddress();
if (registry.code.length == 0) revert PositionManagerErrors.NotContract();
if (!IOperationAuthorizationRegistry(registry).IS_PRODUCTION_REGISTRY()) {
revert PositionManagerErrors.NotProductionRegistry();
}
address oldRegistry = address(authorizationRegistry);
authorizationRegistry = IOperationAuthorizationRegistry(registry);
emit AuthorizationRegistryUpdated(oldRegistry, registry, msg.sender, block.timestamp);
}
/**
* @notice Set the PositionManager contract address.
* @dev Only callable by ADMIN_MODULE_ROLE. New address must be a deployed contract.
* @param newPositionManager New PositionManager contract address.
*/
function setPositionManager(address newPositionManager) external onlyAdminModule {
if (newPositionManager == address(0)) revert PositionManagerErrors.InvalidAddress();
if (newPositionManager.code.length == 0) revert PositionManagerErrors.NotContract();
address oldPositionManager = positionManager;
positionManager = newPositionManager;
emit PositionManagerUpdated(oldPositionManager, newPositionManager, msg.sender, block.timestamp);
}
/**
* @notice Set the PositionManagerCore module address (H-1 fix).
* @dev Only callable by ADMIN_MODULE_ROLE. This must point to the PositionManagerCoreModule
* which implements IPositionManagerCore and exposes getPositionDetails().
* @param newPositionManagerCore New PositionManagerCoreModule contract address.
*/
function setPositionManagerCoreModule(address newPositionManagerCore) external onlyAdminModule {
if (newPositionManagerCore == address(0)) revert PositionManagerErrors.InvalidAddress();
if (newPositionManagerCore.code.length == 0) revert PositionManagerErrors.NotContract();
address oldCore = positionManagerCore;
positionManagerCore = newPositionManagerCore;
emit PositionManagerCoreUpdated(oldCore, newPositionManagerCore, msg.sender, block.timestamp);
}
/**
* @notice Pause all contract operations in an emergency.
* @dev Only callable by EMERGENCY_PAUSE_ROLE.
*/
function pause() external onlyRole(EMERGENCY_PAUSE_ROLE) {
_pause();
emit ContractPaused(msg.sender, block.timestamp);
}
/**
* @notice Resume contract operations after an emergency pause.
* @dev Only callable by ADMIN_MODULE_ROLE.
*/
function unpause() external onlyAdminModule {
_unpause();
emit ContractUnpaused(msg.sender, block.timestamp);
}
/**
* @notice Authorise a UUPS implementation upgrade.
* @dev Only callable by DEFAULT_ADMIN_ROLE. Emits ContractUpgraded.
* @param newImplementation Address of the new implementation contract.
*/
function _authorizeUpgrade(address newImplementation)
internal
override
onlyAdminModule
{
if (newImplementation == address(0)) revert PositionManagerErrors.InvalidAddress();
if (newImplementation.code.length == 0) revert PositionManagerErrors.NotContract();
// Emit upgrade event for transparency
emit ContractUpgraded(
ERC1967Utils.getImplementation(),
newImplementation,
VERSION,
block.timestamp
);
}
/**
* @notice Validate that a new implementation is safe to upgrade to.
* @dev Checks for non-zero address and deployed bytecode.
* @param newImplementation New implementation address.
* @return bool True if the upgrade is valid.
*/
function validateUpgrade(address newImplementation) external view returns (bool) {
if (newImplementation == address(0)) revert PositionManagerErrors.InvalidAddress();
if (newImplementation.code.length == 0) revert PositionManagerErrors.NotContract();
try IVersioned(newImplementation).VERSION() returns (string memory version) {
if (bytes(version).length == 0) revert NoVersion();
} catch {
revert MissingVERSION();
}
return true;
}
// =============================================================================
// EVENTS
// =============================================================================
event AdminModuleUpdated(address indexed oldAdminModule, address indexed newAdminModule);
event PositionLiquidated(
bytes32 indexed positionId,
address indexed liquidator,
uint256 collateralRatio,
uint256 debtRepaid,
uint256 collateralValue,
bool wasExpired,
uint256 timestamp
);
event LiquidationParametersUpdated(
uint256 oldLiquidationThreshold,
uint256 newLiquidationThreshold,
uint256 oldMaxLiquidationAmount,
uint256 newMaxLiquidationAmount,
uint256 oldLiquidationTimeout,
uint256 newLiquidationTimeout,
address indexed caller,
uint256 timestamp
);
// Commit-Reveal System Events
event LiquidationCommitted(
bytes32 indexed positionId,
address indexed liquidator,
uint256 quantumTimestamp,
uint256 timestamp
);
event LiquidationRevealed(
bytes32 indexed positionId,
address indexed liquidator,
uint256 quantumTimestamp,
bool success,
uint256 timestamp
);
event UcdControllerUpdated(
address oldUcdController,
address newUcdController,
address indexed caller,
uint256 timestamp
);
event LoanOperationsManagerUpdated(
address indexed oldLoanOperationsManager,
address indexed newLoanOperationsManager,
address indexed caller,
uint256 timestamp
);
event PositionManagerUpdated(
address indexed oldPositionManager,
address indexed newPositionManager,
address indexed caller,
uint256 timestamp
);
event PositionManagerCoreUpdated(
address indexed oldPositionManagerCore,
address indexed newPositionManagerCore,
address indexed caller,
uint256 timestamp
);
event AuthorizationRegistryUpdated(
address indexed oldAuthorizationRegistry,
address indexed newAuthorizationRegistry,
address indexed caller,
uint256 timestamp
);
event LitActionValidatorUpdated(
address indexed oldValidator,
address indexed newValidator,
address indexed caller,
uint256 timestamp
);
event ExpiryLiquidationIncrementUpdated(uint256 oldValue, uint256 newValue, address indexed updatedBy, uint256 timestamp);
event ExpiredLoanGracePeriodUpdated(uint256 oldDays, uint256 newDays, address indexed updatedBy, uint256 timestamp);
event MaxEscalatedThresholdUpdated(uint256 oldThreshold, uint256 newThreshold, address indexed updatedBy, uint256 timestamp);
event ContractPaused(address indexed caller, uint256 timestamp);
event ContractUnpaused(address indexed caller, uint256 timestamp);
event ContractUpgraded(
address indexed oldImplementation,
address indexed newImplementation,
string version,
uint256 timestamp
);
/**
* @dev Compute a per-commitment delay seed at commit time.
* @notice M-7 fix: quantumTimestamp alone is grindable. The LIT Action will sign any quantum
* in the 3-quantum validity window (past/current/next), so a committer can request
* ~3 valid signatures and pick the one yielding the lowest randomized delay. It is
* therefore combined with the commit block's RANDAO mix, which a non-validator
* committer cannot predict when crafting the commit tx — defeating the grind.
* (`block.difficulty` is opcode 0x44; on the london EVM target it is the
* non-deprecated spelling for the post-Merge PREVRANDAO value.)
* This does NOT regress the M-1 fix: M-1 removed block-based entropy as a *sole*
* source because validator-liquidators can influence the RANDAO mix. Here it is
* mixed *with* the LIT-Action-signed quantumTimestamp, so grinding would require
* controlling both — strictly stronger than either source alone.
* @param positionId Position identifier
* @param quantumTimestamp LIT-Action-signed quantum timestamp from the commit call
*/
function _requestVRFRandomness(bytes32 positionId, uint256 quantumTimestamp) internal {
uint256 seed = uint256(keccak256(abi.encodePacked(
positionId,
quantumTimestamp,
block.difficulty
)));
vrfSeeds[positionId] = seed;
}
/**
* @dev Calculate randomized reveal delay using VRF-based entropy
* @param positionId Position identifier
* @param quantumTimestamp Quantum timestamp for additional entropy
* @return uint256 Required delay in seconds
*/
function _calculateRandomizedDelay(bytes32 positionId, uint256 quantumTimestamp) internal view returns (uint256) {
// vrfSeeds[positionId] is always populated by commitLiquidation -> _requestVRFRandomness
// before any reveal (revealAndLiquidate reverts NoCommitmentFound otherwise), so no
// fallback is needed here.
uint256 vrfSeed = vrfSeeds[positionId];
// Combine VRF seed with quantumTimestamp for final entropy
bytes32 finalEntropy = keccak256(abi.encodePacked(
vrfSeed,
quantumTimestamp,
positionId
));
// Generate random additional delay (0 to MAX_RANDOM_DELAY seconds)
uint256 randomDelay = uint256(finalEntropy) % MAX_RANDOM_DELAY;
// Return minimum delay plus random component
return MIN_REVEAL_DELAY + randomDelay;
}
/**
* @notice Check if this contract implements a given interface.
* @dev ERC165 interface support check.
* @param interfaceId ERC165 interface identifier.
* @return bool True if the interface is supported.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable) returns (bool) {
// H-1 (2026-05-17): advertise ILiquidationManager so AdminModule.updateModules()'s
// ERC-165 probe recognises this contract as a valid liquidation-module candidate.
return
interfaceId == type(ILiquidationManager).interfaceId ||
AccessControlEnumerableUpgradeable.supportsInterface(interfaceId);
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "london"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.