Verified contractPartialMIT
Underwriter
Address0x3e2cf3d0e0b8e93310ee6602be7d135df003b655
- Balance
0 ETH
- Transactions
0
- 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
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,082,351
- Creation transaction
- 0x443b4b1d23…2c33ac5cc1
26 files
- src/settlement/Underwriter.solmain26.31 KB
- lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol8.91 KB
- lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol12.23 KB
- lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol1.19 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol4.45 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol192 B
- lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol181 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol6.54 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol9.44 KB
- lib/openzeppelin-contracts/contracts/utils/Address.sol6.03 KB
- lib/openzeppelin-contracts/contracts/utils/Errors.sol896 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.06 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.07 KB
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- src/interfaces/IAuthorizationFlags.sol1.79 KB
- src/interfaces/IBufferedCapitalAccount.sol2.73 KB
- src/interfaces/ICapitalAccount.sol4.51 KB
- src/interfaces/IDalocHub.sol3.31 KB
- src/interfaces/IUnderwriter.sol2.38 KB
- src/shared/BidQueue.sol9.45 KB
- src/shared/Constants.sol1.15 KB
- src/shared/DalocTopics.sol8.82 KB
- src/shared/Errors.sol3.73 KB
- src/shared/ProofExecutorAuth.sol4.17 KB
src/settlement/Underwriter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IAuthorizationFlags} from "../interfaces/IAuthorizationFlags.sol";
import {IBufferedCapitalAccount} from "../interfaces/IBufferedCapitalAccount.sol";
import {ICapitalAccount} from "../interfaces/ICapitalAccount.sol";
import {IDalocHub} from "../interfaces/IDalocHub.sol";
import {IUnderwriterLP} from "../interfaces/IUnderwriter.sol";
import {BidQueue} from "../shared/BidQueue.sol";
import {BPS_SCALE, WAD} from "../shared/Constants.sol";
import {DalocTopics} from "../shared/DalocTopics.sol";
import {
AlreadyRegistered,
ExposureAlreadyRegistered,
ExposureExceedsRegistered,
InsufficientAllowance,
InsufficientBuffer,
InsufficientLiquidity,
NotFlagged,
NotInQueue,
QueueFull,
TransferMismatch,
ZeroAddress,
ZeroAmount,
ZeroNavWithSupply
} from "../shared/Errors.sol";
import {ProofExecutorOrExecutorAuth} from "../shared/ProofExecutorAuth.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
/// @title Underwriter
/// @notice IBufferedCapitalAccount — LP capital account with first-loss buffer. Phase-agnostic.
///
/// LPs participate by granting USDC allowance to this contract and registering with
/// a bid (0-1000 BPS). Higher bidders are drawn first during origination. The bid fee
/// materialises as share dilution — the LP receives fewer shares per USDC drawn.
///
/// NAV = totalExposure + lpLiquid
/// (lpLiquid = _trackedBalance − bufferBalance; LP allowances excluded until drawn)
/// sharePrice = NAV * WAD / totalSupply (with virtual offset for first-deposit protection)
///
/// ──────────────────────────────────────────────────────────────────────
/// SCOPE — what this contract IS responsible for:
/// • IBufferedCapitalAccount implementation: deployCapital (draw from LP queue),
/// track (register position exposure), settle (decrement exposure, credit capital),
/// writeOff (bad-debt absorption from buffer then NAV), credit (late delivery).
/// • Buffer management: fundBuffer (permissionless first-loss deposit),
/// drawBuffer (PE-gated deployment), releaseBuffer (close/liquidation cleanup).
/// Buffer is true first-loss capital invisible to NAV.
/// • LP share management: ERC-20 shares, BidQueue priority ordering,
/// register/deregister/updateBid, redeem (against non-buffer liquid).
/// • NAV computation: totalExposure + max(0, _trackedBalance − bufferBalance).
/// Uses _trackedBalance (not raw USDC.balanceOf) to prevent donation inflation.
///
/// ANTI-SCOPE — what this contract MUST NEVER do:
/// • Never hold collateral — only USDC principal and buffers.
/// • Never interact with lending venues or DEXes.
/// • Never make lifecycle decisions — all functions are phase-agnostic generic
/// primitives. The contract does not know which phase is calling it.
/// • Never compute interest — interest is realized once, at close Phase2, from the
/// collateral side; the on-chain debt ledger is a pure 1:1 note.
/// • Never decide liquidation — enforcement circuit + AuthorizationFlags decide.
/// • Never hold position-specific logic — settle() decrements (not zeroes)
/// exposure, enabling future multi-resize without contract changes.
///
/// JUSTIFICATION:
/// Capital accounting must be orthogonal to lifecycle phases. The same settle()
/// call serves close, liquidation, and resize identically — the caller determines
/// the amounts, not Underwriter. Buffer as first-loss capital invisible to NAV
/// ensures LP share price is unaffected by buffer movements. The BidQueue enables
/// competitive LP pricing without protocol intervention.
///
/// PRODUCT SPACE — P = {VF,LF} × {Direct,Swap} × {Borrower,UndercollatMA,OvercollatMA} × {SameChain,CrossChain}:
/// All 18 valid points use Underwriter identically. The contract has zero
/// awareness of which dimension combination produced the capital flow.
/// Buffer is always committed regardless of CS/CH/CD/GEO.
///
/// REUSE — lifecycle phases that call this contract's primitives:
/// • Creation Phase1: deployCapital (draw LP capital), track (register exposure),
/// fundBuffer × N (rate + option + origFee buffers)
/// • Close Phase2: releaseBuffer, settle (return capital + clear exposure)
/// • Enforcement Phase1: (no direct UW calls — flags written on AuthorizationFlags)
/// • Liquidation: writeOff, releaseBuffer, settle (via LiquidationExecutor)
/// • Liquidation Phase1 (cross-chain): settle or credit
/// • Resize: settle (partial exposure decrement), deployCapital (re-draw)
/// • Permissionless: fundBuffer (anyone can refill), redeem (LP withdrawal)
/// ──────────────────────────────────────────────────────────────────────
contract Underwriter is
Initializable,
IUnderwriterLP,
ERC20Upgradeable,
ReentrancyGuardTransient,
ProofExecutorOrExecutorAuth
{
using SafeERC20 for IERC20;
using BidQueue for BidQueue.Queue;
uint256 private constant MIN_DEAD_SHARES = 1e6;
uint256 private constant MAX_LP_QUEUE = 256;
uint256 private constant MIN_REGISTRATION_ALLOWANCE = 1000e6;
// ── Storage layout (proxy storage; sequential from slot 0 — OZ bases are ERC-7201 namespaced and consume no sequential slots) ──
// Circuit-verified — DO NOT reorder slots 0-2.
// slot 0: bufferBalance — circuit reads
// slot 1: totalExposure — circuit reads
// slot 2: _trackedBalance
// slots 3–7: bidQueue (size, nonce, tree, indexOf, idAt)
// slot 8: isRegistered
// slot 9: positionWrittenOff
// slot 10: positionExposure
// slots 11–60: __gap (future-proofing)
// ERC-20 balances/allowances/supply live in the ERC-7201 `openzeppelin.storage.ERC20`
// namespace of ERC20Upgradeable and consume no sequential slots.
uint256 public bufferBalance; // slot 0 — circuit reads
uint256 public override totalExposure; // slot 1 — circuit reads
uint256 private _trackedBalance; // slot 2
BidQueue.Queue internal bidQueue; // slots 3-7 (size, nonce, tree, indexOf, idAt)
mapping(address => bool) public isRegistered; // slot 8
mapping(bytes32 => uint256) public positionWrittenOff; // slot 9
mapping(bytes32 => uint256) public positionExposure; // slot 10
uint256[50] private __gap;
IERC20 public immutable USDC;
IDalocHub public immutable HUB;
IAuthorizationFlags public immutable AUTHORIZATION_FLAGS;
/// @param usdc_ Immutable reserve token (USDC) drawn from LPs and buffered.
/// @param proofExecutor_ Immutable ProofExecutor address.
/// @param liquidationExecutor_ Immutable LiquidationExecutor address.
/// @param hub_ Immutable DalocHub address for event routing.
/// @param authorizationFlags_ Immutable AuthorizationFlags for write-off gating.
constructor(
address usdc_,
address proofExecutor_,
address liquidationExecutor_,
address hub_,
address authorizationFlags_
) ProofExecutorOrExecutorAuth(proofExecutor_, liquidationExecutor_) {
if (usdc_ == address(0) || hub_ == address(0) || authorizationFlags_ == address(0)) revert ZeroAddress();
USDC = IERC20(usdc_);
HUB = IDalocHub(hub_);
AUTHORIZATION_FLAGS = IAuthorizationFlags(authorizationFlags_);
_disableInitializers();
}
/// @notice Initialize the proxy — per-instance ERC-20 name/symbol are proxy storage.
/// Called immediately after deployment, in the same transaction.
/// @param name_ ERC-20 share token name.
/// @param symbol_ ERC-20 share token symbol.
/// @dev Re-initialization reverts via OZ Initializable (InvalidInitialization).
function initialize(
string memory name_,
string memory symbol_
) external initializer {
__ERC20_init(name_, symbol_);
}
function _entryId(
address lp
) private pure returns (bytes32) {
return bytes32(uint256(uint160(lp)));
}
function _lpFromEntryId(
bytes32 id
) private pure returns (address) {
// forge-lint: disable-next-line(unsafe-typecast)
return address(uint160(uint256(id)));
}
// ═══════════════════════════════════════════════════════════════════════════
// LP MANAGEMENT
// ═══════════════════════════════════════════════════════════════════════════
/// @inheritdoc IUnderwriterLP
function register(
uint16 bidBps
) external override {
if (isRegistered[msg.sender]) revert AlreadyRegistered();
if (bidQueue.size >= MAX_LP_QUEUE) revert QueueFull();
if (USDC.allowance(msg.sender, address(this)) < MIN_REGISTRATION_ALLOWANCE) revert InsufficientAllowance();
isRegistered[msg.sender] = true;
bidQueue.insert(_entryId(msg.sender), bidBps);
HUB.emitLog(DalocTopics.TOPIC_LP_REGISTERED, abi.encode(msg.sender, bidBps));
}
/// @inheritdoc IUnderwriterLP
function deregister() external override {
if (!isRegistered[msg.sender]) revert NotInQueue();
// Deregistration only sheds the caller's own access; the hub event two
// lines down is the (hub-relayed) deregistration record.
// forge-lint: disable-next-line(missing-events-access-control)
isRegistered[msg.sender] = false;
bidQueue.remove(_entryId(msg.sender));
HUB.emitLog(DalocTopics.TOPIC_LP_DEREGISTERED, abi.encode(msg.sender));
}
/// @inheritdoc IUnderwriterLP
function updateBid(
uint16 newBidBps
) external override {
if (!isRegistered[msg.sender]) revert NotInQueue();
bytes32 eid = _entryId(msg.sender);
uint16 oldBid = bidQueue.bidOf(eid);
bidQueue.updateBid(eid, newBidBps);
HUB.emitLog(DalocTopics.TOPIC_LP_BID_UPDATED, abi.encode(msg.sender, oldBid, newBidBps));
}
// ═══════════════════════════════════════════════════════════════════════════
// CAPITAL DEPLOYMENT (PROOF-EXECUTOR)
// ═══════════════════════════════════════════════════════════════════════════
/// @notice Deploy capital by drawing from LPs in bid-priority order.
/// LPs stay registered after draws — only truly dead LPs (zero allowance) are evicted.
/// Bid fee materialises as share dilution: LP receives shares for (draw - bidFee).
function deployCapital(
uint256 amount,
address recipient
) external override nonReentrant onlyProofExecutor {
if (amount == 0) revert ZeroAmount();
if (recipient == address(0)) revert ZeroAddress();
if (recipient == address(this)) revert ZeroAddress();
uint256 remaining = amount;
uint256 currentPrice = sharePrice();
uint256 supply = totalSupply();
if (supply > 0 && currentPrice == 0) revert ZeroNavWithSupply();
uint256 maxPops = bidQueue.size;
bytes32[] memory stashedIds = new bytes32[](maxPops);
uint16[] memory stashedBids = new uint16[](maxPops);
uint240[] memory stashedNonces = new uint240[](maxPops);
uint256 stashCount = 0;
while (remaining > 0 && bidQueue.size > 0) {
(bytes32 eid, uint16 bidBps, uint240 regNonce) = bidQueue.popFull();
address lp = _lpFromEntryId(eid);
uint256 allowance = USDC.allowance(lp, address(this));
uint256 balance = USDC.balanceOf(lp);
uint256 available = allowance < balance ? allowance : balance;
if (available == 0) {
isRegistered[lp] = false;
HUB.emitLog(DalocTopics.TOPIC_LP_DEREGISTERED, abi.encode(lp));
continue;
}
uint256 draw = available < remaining ? available : remaining;
USDC.safeTransferFrom(lp, address(this), draw);
_trackedBalance += draw;
uint256 bidFee = 0;
uint256 netForShares = draw;
if (supply > 0 && bidBps > 0) {
bidFee = (draw * bidBps + BPS_SCALE - 1) / BPS_SCALE;
netForShares = draw - bidFee;
}
uint256 shares;
if (supply == 0) {
if (draw < MIN_DEAD_SHARES) revert ZeroAmount();
shares = draw;
_mint(address(1), MIN_DEAD_SHARES);
_mint(lp, shares - MIN_DEAD_SHARES);
supply = totalSupply();
} else {
shares = currentPrice > 0 ? (netForShares * WAD) / currentPrice : netForShares;
if (shares == 0) revert ZeroAmount();
_mint(lp, shares);
supply += shares;
}
remaining -= draw;
stashedIds[stashCount] = eid;
stashedBids[stashCount] = bidBps;
stashedNonces[stashCount] = regNonce;
stashCount++;
HUB.emitLog(DalocTopics.TOPIC_CAPITAL_DRAWN, abi.encode(lp, draw, shares, bidFee));
}
for (uint256 k = 0; k < stashCount;) {
bidQueue.reinsert(stashedIds[k], stashedBids[k], stashedNonces[k]);
unchecked {
++k;
}
}
if (remaining > 0) revert InsufficientLiquidity();
_trackedBalance -= amount;
USDC.forceApprove(recipient, amount);
HUB.emitLog(DalocTopics.TOPIC_CAPITAL_DEPLOYMENT_COMPLETED, abi.encode(amount, recipient, totalExposure));
}
// ═══════════════════════════════════════════════════════════════════════════
// SETTLEMENT (PROOF-EXECUTOR)
// ═══════════════════════════════════════════════════════════════════════════
/// @inheritdoc ICapitalAccount
function track(
bytes32 positionId,
uint256 amount
) external nonReentrant onlyProofExecutor {
_track(positionId, amount);
}
/// @inheritdoc ICapitalAccount
function settle(
bytes32 positionId,
uint256 capitalAmount,
uint256 exposureAmount
) external nonReentrant onlyProofExecutorOrExecutor {
_settle(positionId, capitalAmount, exposureAmount);
}
// ═══════════════════════════════════════════════════════════════════════════
// BUFFER
// ═══════════════════════════════════════════════════════════════════════════
/// @inheritdoc IBufferedCapitalAccount
function fundBuffer(
uint256 amount
) external nonReentrant {
if (amount == 0) revert ZeroAmount();
USDC.safeTransferFrom(msg.sender, address(this), amount);
bufferBalance += amount;
_trackedBalance += amount;
HUB.emitLog(DalocTopics.TOPIC_BUFFER_FUNDED, abi.encode(msg.sender, amount));
}
/// @inheritdoc IBufferedCapitalAccount
function drawBuffer(
uint256 amount,
address recipient
) external override nonReentrant onlyProofExecutor {
if (amount == 0) revert ZeroAmount();
if (recipient == address(0)) revert ZeroAddress();
if (amount > bufferBalance) revert InsufficientBuffer();
bufferBalance -= amount;
_trackedBalance -= amount;
USDC.safeTransfer(recipient, amount);
HUB.emitLog(DalocTopics.TOPIC_BUFFER_DRAWN, abi.encode(amount, recipient));
}
/// @inheritdoc IBufferedCapitalAccount
function releaseBuffer(
uint256 amount
) external nonReentrant onlyProofExecutorOrExecutor {
if (amount == 0) revert ZeroAmount();
if (amount > bufferBalance) revert InsufficientBuffer();
bufferBalance -= amount;
HUB.emitLog(DalocTopics.TOPIC_BUFFER_RELEASED, abi.encode(amount));
}
// ═══════════════════════════════════════════════════════════════════════════
// REDEEM
// ═══════════════════════════════════════════════════════════════════════════
/// @inheritdoc IUnderwriterLP
function redeem(
uint256 shares
) external override nonReentrant {
if (shares == 0) revert ZeroAmount();
if (balanceOf(msg.sender) < shares) revert InsufficientLiquidity();
uint256 price = sharePrice();
uint256 payout = (shares * price) / WAD;
if (payout == 0) revert ZeroAmount();
uint256 liquid = _trackedBalance > bufferBalance ? _trackedBalance - bufferBalance : 0;
if (payout > liquid) revert InsufficientLiquidity();
_burn(msg.sender, shares);
_trackedBalance -= payout;
USDC.safeTransfer(msg.sender, payout);
HUB.emitLog(DalocTopics.TOPIC_SHARES_REDEEMED, abi.encode(msg.sender, shares, payout));
}
// ═══════════════════════════════════════════════════════════════════════════
// VIEWS
// ═══════════════════════════════════════════════════════════════════════════
/// @inheritdoc ICapitalAccount
function nav() public view override returns (uint256 navValue) {
uint256 lpLiquid = _trackedBalance > bufferBalance ? _trackedBalance - bufferBalance : 0;
navValue = totalExposure + lpLiquid;
}
/// @inheritdoc ICapitalAccount
function sharePrice() public view override returns (uint256 price) {
uint256 supply = totalSupply();
if (supply == 0) return WAD;
price = (nav() * WAD) / supply;
}
/// @inheritdoc IUnderwriterLP
function queueSize() external view override returns (uint256) {
return bidQueue.size;
}
/// @inheritdoc IUnderwriterLP
function headLp() external view override returns (address lp) {
if (bidQueue.size == 0) return address(0);
(bytes32 eid,) = bidQueue.peek();
lp = _lpFromEntryId(eid);
}
/// @inheritdoc IUnderwriterLP
function totalAvailableLiquidity() external view override returns (uint256 total) {
uint256 n = bidQueue.size;
for (uint256 i = 1; i <= n;) {
bytes32 eid = bidQueue.entryAt(i);
address lp = _lpFromEntryId(eid);
uint256 allowance = USDC.allowance(lp, address(this));
uint256 balance = USDC.balanceOf(lp);
total += allowance < balance ? allowance : balance;
unchecked {
++i;
}
}
}
// ═══════════════════════════════════════════════════════════════════════════
// WRITE-OFF
// ═══════════════════════════════════════════════════════════════════════════
/// @inheritdoc ICapitalAccount
function writeOff(
bytes32 positionId,
uint256 amount
) external nonReentrant onlyProofExecutorOrExecutor {
_writeOff(positionId, amount);
}
// ═══════════════════════════════════════════════════════════════════════════
// INTERNAL IMPLEMENTATIONS
// ═══════════════════════════════════════════════════════════════════════════
function _track(
bytes32 positionId,
uint256 amount
) internal {
if (amount == 0) revert ZeroAmount();
if (positionExposure[positionId] > 0) revert ExposureAlreadyRegistered();
positionExposure[positionId] = amount;
totalExposure += amount;
HUB.emitLog(DalocTopics.TOPIC_EXPOSURE_REGISTERED, abi.encode(positionId, amount));
}
function _settle(
bytes32 positionId,
uint256 capitalAmount,
uint256 exposureAmount
) internal {
if (capitalAmount == 0 && exposureAmount == 0) revert ZeroAmount();
if (exposureAmount > positionExposure[positionId]) revert ExposureExceedsRegistered();
if (exposureAmount > 0) positionExposure[positionId] -= exposureAmount;
if (capitalAmount > 0) {
uint256 actual = USDC.balanceOf(address(this));
if (actual < _trackedBalance + capitalAmount) revert TransferMismatch();
_trackedBalance += capitalAmount;
}
uint256 alreadyWrittenOff = positionWrittenOff[positionId];
uint256 effective = exposureAmount > alreadyWrittenOff ? exposureAmount - alreadyWrittenOff : 0;
if (alreadyWrittenOff > 0) {
uint256 consumed = exposureAmount < alreadyWrittenOff ? exposureAmount : alreadyWrittenOff;
positionWrittenOff[positionId] -= consumed;
}
uint256 newExposure = totalExposure;
if (effective > 0) {
newExposure = effective >= newExposure ? 0 : newExposure - effective;
totalExposure = newExposure;
}
HUB.emitLog(DalocTopics.TOPIC_CAPITAL_RETURNED, abi.encode(positionId, capitalAmount));
HUB.emitLog(
DalocTopics.TOPIC_EXPOSURE_DECREASED, abi.encode(positionId, exposureAmount, effective, newExposure)
);
}
function _writeOff(
bytes32 positionId,
uint256 amount
) internal {
if (!AUTHORIZATION_FLAGS.isAuthorized(positionId)) revert NotFlagged();
if (amount == 0) revert ZeroAmount();
uint256 registered = positionExposure[positionId];
if (registered == 0) revert ZeroAmount();
uint256 alreadyWrittenOff = positionWrittenOff[positionId];
uint256 remaining = registered > alreadyWrittenOff ? registered - alreadyWrittenOff : 0;
if (remaining == 0) revert ZeroAmount();
uint256 wo = amount < remaining ? amount : remaining;
wo = wo < totalExposure ? wo : totalExposure;
positionWrittenOff[positionId] += wo;
uint256 bufferAbsorbed = wo < bufferBalance ? wo : bufferBalance;
bufferBalance -= bufferAbsorbed;
uint256 exposure = totalExposure - wo;
totalExposure = exposure;
HUB.emitLog(DalocTopics.TOPIC_EXPOSURE_WRITTEN_OFF, abi.encode(positionId, wo, exposure));
}
// ═══════════════════════════════════════════════════════════════════════════
// ICapitalAccount: CREDIT (late USDC delivery after exposure cleared)
// ═══════════════════════════════════════════════════════════════════════════
/// @inheritdoc ICapitalAccount
function credit(
bytes32 positionId,
uint256 amount
) external nonReentrant onlyProofExecutor {
_settle(positionId, amount, 0);
}
/// @inheritdoc IUnderwriterLP
function pruneQueue() external override {
uint256 n = bidQueue.size;
if (n == 0) return;
bytes32[] memory dead = new bytes32[](n);
uint256 deadCount = 0;
for (uint256 i = 1; i <= n;) {
bytes32 eid = bidQueue.entryAt(i);
address lp = _lpFromEntryId(eid);
if (USDC.allowance(lp, address(this)) < MIN_REGISTRATION_ALLOWANCE) dead[deadCount++] = eid;
unchecked {
++i;
}
}
for (uint256 j = 0; j < deadCount;) {
address lp = _lpFromEntryId(dead[j]);
isRegistered[lp] = false;
bidQueue.remove(dead[j]);
HUB.emitLog(DalocTopics.TOPIC_LP_DEREGISTERED, abi.encode(lp));
unchecked {
++j;
}
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
lib/openzeppelin-contracts/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert Errors.FailedCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
lib/openzeppelin-contracts/contracts/utils/Errors.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
src/interfaces/IAuthorizationFlags.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @title IAuthorizationFlags
/// @notice Per-position authorization flags with monotonic version counter.
/// Written by the ProofExecutor when an enforcement proof verifies a health factor breach —
/// enforcement Phase1, on the collateral chain where liquidation happens (the only chain
/// whose instance is ever written).
/// Read by the Underwriter/CuratorVault write-off gating and the LiquidationExecutor's
/// liquidator-side snapshot.
interface IAuthorizationFlags {
struct Flag {
bool authorized;
uint64 version;
uint64 setBlock;
}
/// @notice Writes an authorization flag after enforcement proof verification.
/// @param positionId Unique position identifier: keccak256(abi.encode(PositionTerms)).
/// @param observationBlock Block number at which HF breach was observed.
/// @param observationTimestamp Timestamp at which HF breach was observed.
/// @param factHash Hash of the enforcement proof output for audit trail.
function write(
bytes32 positionId,
uint256 observationBlock,
uint256 observationTimestamp,
bytes32 factHash
) external;
/// @notice Clears an authorization flag (e.g., after borrower rescue repayment).
function clear(
bytes32 positionId,
uint256 observationBlock,
uint256 observationTimestamp,
bytes32 factHash
) external;
/// @notice Reads the current flag state for a position.
function flags(
bytes32 positionId
) external view returns (bool authorized, uint64 version);
/// @notice Returns only the authorization status (TTL-enforced).
function isAuthorized(
bytes32 positionId
) external view returns (bool);
}
src/interfaces/IBufferedCapitalAccount.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {ICapitalAccount} from "./ICapitalAccount.sol";
/// @title IBufferedCapitalAccount
/// @notice Capital account extended with first-loss buffer operations.
///
/// Only the Underwriter implements this — CuratorVault implements ICapitalAccount
/// directly because vaults have no buffer mechanics (their entire balance is at-risk
/// capital, not partitioned into first-loss and LP liquid).
///
/// ──────────────────────────────────────────────────────────────────────
/// SCOPE — what this interface adds beyond ICapitalAccount:
/// • fundBuffer(amount) — permissionless buffer deposit. Anyone can recapitalize
/// the first-loss buffer (non-dilutive: no shares minted).
/// • drawBuffer(amount, recipient) — PE-gated buffer deployment to a position.
/// Used during creation to commit rate + option + origFee buffers.
/// • releaseBuffer(amount) — PE-or-LE-gated buffer return at close/liquidation.
/// Buffer funds return to the Underwriter's tracked balance (NAV-neutral:
/// buffer is invisible to share price by design).
/// • bufferBalance() — current first-loss buffer size (circuit reads slot 5).
///
/// ANTI-SCOPE:
/// • Never held by CuratorVault — vaults are full-risk, no first-loss partition.
/// • Buffer operations are NAV-neutral — buffer is explicitly excluded from nav()
/// computation. Violating this inflates share price.
///
/// JUSTIFICATION:
/// Buffer as first-loss capital invisible to NAV ensures LP share price is
/// unaffected by buffer movements. A $1M write-off with $300K
/// buffer means LPs bear only $700K — the buffer absorbs the first loss. This
/// creates an asymmetric risk profile that enables higher leverage (κ ≈ 20 for LF).
///
/// REUSE:
/// • fundBuffer: Permissionless recap (anyone, anytime)
/// • drawBuffer: Creation Phase1 (commit rate + option + origFee buffers)
/// • releaseBuffer: Close Phase2 + Liquidation (via LE) + Resize
/// ──────────────────────────────────────────────────────────────────────
interface IBufferedCapitalAccount is ICapitalAccount {
function fundBuffer(
uint256 amount
) external;
function drawBuffer(
uint256 amount,
address recipient
) external;
function releaseBuffer(
uint256 amount
) external;
function bufferBalance() external view returns (uint256);
}
src/interfaces/ICapitalAccount.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @title ICapitalAccount
/// @notice Polymorphic capital account interface — the fundamental abstraction for ALL
/// capital-holding entities in the protocol (Underwriter, CuratorVault).
///
/// Provides the orthogonal basis for capital deployment, exposure tracking, and
/// settlement. LiquidationExecutor and ProofExecutor cast callee addresses to this
/// interface for dimension-independent capital operations.
///
/// ──────────────────────────────────────────────────────────────────────
/// SCOPE — what this interface defines:
/// Seven orthogonal primitives that compose ALL capital lifecycle phases:
/// • deployCapital(amount, recipient) — draw capital and approve recipient to pull it.
/// • track(positionId, amount) — register position exposure (creation-time).
/// • settle(positionId, capitalAmount, exposureAmount) — credit returned capital,
/// decrement (not zero) exposure. Used by close, liquidation, and resize.
/// • writeOff(positionId, amount) — absorb bad debt (buffer first, then NAV).
/// • credit(positionId, amount) — late capital delivery after exposure is cleared.
/// Replaces the former specialty `receiveLateClaim` with a generic primitive.
/// Used by Liquidation Phase2 residual USDC routing.
/// • nav() — total asset value (exposure + liquid, excluding buffer).
/// • sharePrice() — NAV per share (for LP share pricing and redemption).
///
/// ANTI-SCOPE — what implementors MUST NEVER do:
/// • Never compute interest — interest is realized once, at close Phase2, from the
/// collateral side; the on-chain debt ledger is a pure 1:1 note.
/// • Never hold collateral — only principal tokens (USDC).
/// • Never make lifecycle decisions — the caller determines amounts.
/// • Never interact with venues or DEXes — pure capital accounting.
///
/// JUSTIFICATION:
/// Capital accounting must be orthogonal to lifecycle phases. The same settle()
/// call serves close (cooperative), liquidation (adversarial), and resize (partial)
/// identically — the caller determines the amounts, not the capital account.
/// `credit()` as a generic "late delivery" primitive eliminates the need for
/// specialty functions like receiveLateClaim, keeping the interface minimal and
/// composable. Every function is used by multiple lifecycle phases — no function
/// exists for a single call site (the core orthogonality requirement).
///
/// PRODUCT SPACE — P = {VF,LF} × {Direct,Swap} × {Borrower,UndercollatMA,OvercollatMA} × {SC,XC}:
/// All 18 valid points use ICapitalAccount identically. The interface has zero
/// awareness of which dimension combination produced the capital flow. This is
/// the "Deep Module" principle (Ousterhout): powerful functionality behind a
/// simple 7-function interface that hides enormous settlement complexity.
///
/// REUSE — lifecycle phases that call these primitives:
/// • deployCapital: Creation Phase1 (draw LP capital to position)
/// • track: Creation Phase1 (register position exposure on UW)
/// • settle: Close Phase2, Liquidation (via LE), Resize (partial exposure decrement)
/// • writeOff: Liquidation (via LE, buffer absorption)
/// • credit: Liquidation Phase2 (cross-chain residual USDC delivery to UW)
/// • nav/sharePrice: Underwriter LP management (redeem, share pricing)
/// ──────────────────────────────────────────────────────────────────────
interface ICapitalAccount {
function deployCapital(
uint256 amount,
address recipient
) external;
function track(
bytes32 positionId,
uint256 amount
) external;
function settle(
bytes32 positionId,
uint256 capitalAmount,
uint256 exposureAmount
) external;
function writeOff(
bytes32 positionId,
uint256 amount
) external;
function credit(
bytes32 positionId,
uint256 amount
) external;
function nav() external view returns (uint256);
function sharePrice() external view returns (uint256);
function totalExposure() external view returns (uint256);
}
src/interfaces/IDalocHub.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @title IDalocHub
/// @notice Central registry, event emitter, and governance surface for DALOC markets.
/// All protocol events are emitted via `emitLog` as unified `DalocLog(topic, data, nonce)`.
interface IDalocHub {
/// @notice One-time proxy initialization: grants `DEFAULT_ADMIN_ROLE` to `admin`
/// and seeds the initial FactsRegistry. Called by the deployer in the same
/// transaction that deploys the BeaconProxy.
/// @param admin Address granted `DEFAULT_ADMIN_ROLE` (the timelock).
/// @param factsRegistry_ Initial FactsRegistry contract (must be non-zero).
function initialize(
address admin,
address factsRegistry_
) external;
/// @notice Returns true when the protocol is globally paused.
function isPaused() external view returns (bool);
/// @notice The active FactsRegistry contract used for proof verification.
function factsRegistry() external view returns (address);
/// @notice Returns the current global log nonce (last emitted value).
function logNonce() external view returns (uint256);
/// @notice Whether a signer has cancelled a specific intent on-chain.
/// @param signer Address that signed the intent.
/// @param intentHash Hash of the intent to check.
/// @return True if the intent was cancelled by the signer.
function cancelledIntents(
address signer,
bytes32 intentHash
) external view returns (bool);
/// @notice Permanently cancels an intent. Called by borrower or their delegate.
/// @param intentHash Hash of the intent to cancel.
function cancelIntent(
bytes32 intentHash
) external;
/// @notice AccessControl role check.
/// @param role Role identifier to query.
/// @param account Address to check.
/// @return True if `account` holds `role`.
function hasRole(
bytes32 role,
address account
) external view returns (bool);
/// @notice Grants a role to an account. Restricted to DEFAULT_ADMIN_ROLE.
/// @param role Role identifier to grant.
/// @param account Recipient account (must be non-zero).
function grantRole(
bytes32 role,
address account
) external;
/// @notice Emits a `DalocLog` event. Caller must hold EMITTER_ROLE.
/// @param topic Domain-specific event selector (keccak256 of event name).
/// @param data ABI-encoded event payload.
function emitLog(
bytes32 topic,
bytes calldata data
) external;
/// @notice Grants EMITTER_ROLE to an address. Restricted to EMITTER_REGISTRAR_ROLE.
/// @param emitter Contract address to authorize (must be non-zero).
function registerEmitter(
address emitter
) external;
/// @notice Pause all protocol activity gated by `isPaused()`.
function pause() external;
/// @notice Resume protocol activity after a pause.
function unpause() external;
/// @notice Update the FactsRegistry address. Restricted to DEFAULT_ADMIN_ROLE
/// (the TimelockController — the 24 h delay lives in the timelock, not here).
/// @param factsRegistry_ New registry address (must be non-zero).
function setFactsRegistry(
address factsRegistry_
) external;
}
src/interfaces/IUnderwriter.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {IBufferedCapitalAccount} from "./IBufferedCapitalAccount.sol";
/// @title IUnderwriter
/// @notice Underwriter-specific marker interface. Inherits ALL capital operations from
/// ICapitalAccount (track, settle, writeOff, credit, deployCapital, nav, sharePrice) and
/// ALL buffer operations from IBufferedCapitalAccount (fundBuffer, drawBuffer, releaseBuffer).
///
/// This interface is intentionally EMPTY — all behavior lives in the parent interfaces.
/// It exists solely as a type tag so callers can distinguish Underwriter from CuratorVault
/// when both implement ICapitalAccount. The generic primitives (7 capital + 4 buffer = 11
/// total functions) are the COMPLETE API for all lifecycle interactions.
///
/// Generic capital operations (track, settle, writeOff, credit) live in ICapitalAccount.
/// Buffer operations (fundBuffer, drawBuffer, releaseBuffer, bufferBalance) live in IBufferedCapitalAccount.
/// `deployCapital` (overridden for LP queue pull) lives in ICapitalAccount.
interface IUnderwriter is IBufferedCapitalAccount {}
/// @title IUnderwriterLP
/// @notice Extended LP management functions specific to Underwriter (not CuratorVault).
interface IUnderwriterLP is IUnderwriter {
/// @notice Register the caller as an LP with the given bid priority (0-1000 BPS).
function register(
uint16 bidBps
) external;
/// @notice Remove the caller from the LP queue.
function deregister() external;
/// @notice Update the caller's queue bid priority (0-1000 BPS).
function updateBid(
uint16 newBidBps
) external;
/// @notice Redeem LP shares for underlying USDC.
function redeem(
uint256 shares
) external;
/// @notice Total exposure across all active positions.
function totalExposure() external view returns (uint256);
/// @notice Number of LPs in the priority queue.
function queueSize() external view returns (uint256);
/// @notice Address of the current highest-priority LP.
function headLp() external view returns (address lp);
/// @notice Effective available liquidity across all registered LPs.
function totalAvailableLiquidity() external view returns (uint256 total);
/// @notice Remove dead LPs (insufficient allowance) from the queue.
function pruneQueue() external;
}
src/shared/BidQueue.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {MAX_BID_BPS} from "./Constants.sol";
import {BidTooHigh} from "./Errors.sol";
/// @title BidQueue — indexed max-heap for prioritised queue ordering.
///
/// Users bid 0–1000 BPS for priority; ties broken FIFO by registration nonce.
/// Hold-and-place sift saves ~30% gas vs swap-per-level.
///
/// The library is consumer-agnostic: Underwriter uses address-as-entryId
/// (pop-stash-reinsert to preserve LP registration across draws),
/// CuratorVault uses nonce-based entryId (pop-consume-reinsert).
library BidQueue {
error BQ_EmptyQueue();
error BQ_DuplicateEntry();
error BQ_EntryNotFound();
struct Queue {
uint256 size;
uint240 nonce;
/// 1-indexed heap: position => packed priority.
mapping(uint256 => uint256) tree;
/// entryId => heap position (0 = absent).
mapping(bytes32 => uint256) indexOf;
/// heap position => entryId.
mapping(uint256 => bytes32) idAt;
}
// ═══════════════════════════════════════════════════════════════════════════
// Packed priority: top 16 bits = bidBps, bottom 240 bits = inverted nonce.
// Higher packed value = higher priority. FIFO tiebreak via inverted nonce.
// ═══════════════════════════════════════════════════════════════════════════
function _pack(
uint16 bidBps,
uint240 regNonce
) private pure returns (uint256) {
return (uint256(bidBps) << 240) | (type(uint240).max - regNonce);
}
function _bidOf(
uint256 packed
) private pure returns (uint16) {
// forge-lint: disable-next-line(unsafe-typecast)
return uint16(packed >> 240);
}
function _nonceOf(
uint256 packed
) private pure returns (uint240) {
// forge-lint: disable-next-line(unsafe-typecast)
return type(uint240).max - uint240(packed);
}
// ═══════════════════════════════════════════════════════════════════════════
// Public API
// ═══════════════════════════════════════════════════════════════════════════
/// Insert a new entry with the given bid. Allocates a fresh registration nonce.
function insert(
Queue storage q,
bytes32 id,
uint16 bidBps
) internal {
if (bidBps > MAX_BID_BPS) revert BidTooHigh();
if (q.indexOf[id] != 0) revert BQ_DuplicateEntry();
uint240 regNonce = q.nonce++;
uint256 packed = _pack(bidBps, regNonce);
uint256 pos = ++q.size;
q.tree[pos] = packed;
q.indexOf[id] = pos;
q.idAt[pos] = id;
_siftUp(q, pos);
}
/// Remove an entry by id. Caller must ensure the entry exists.
function remove(
Queue storage q,
bytes32 id
) internal {
uint256 pos = q.indexOf[id];
if (pos == 0) revert BQ_EntryNotFound();
uint256 last = q.size;
if (pos == last) {
// Removing the last element — no sift needed.
delete q.tree[last];
delete q.indexOf[id];
delete q.idAt[last];
q.size = last - 1;
return;
}
// Move last element into the removed position.
bytes32 lastId = q.idAt[last];
uint256 lastPacked = q.tree[last];
q.tree[pos] = lastPacked;
q.indexOf[lastId] = pos;
q.idAt[pos] = lastId;
delete q.tree[last];
delete q.indexOf[id];
delete q.idAt[last];
q.size = last - 1;
// Sift in the direction that restores the heap property.
if (pos > 1 && lastPacked > q.tree[pos / 2]) _siftUp(q, pos);
else _siftDown(q, pos);
}
/// Update bid for an existing entry. Preserves the original registration nonce.
/// No-op if bid is unchanged (prevents accidental nonce loss).
function updateBid(
Queue storage q,
bytes32 id,
uint16 newBidBps
) internal {
if (newBidBps > MAX_BID_BPS) revert BidTooHigh();
uint256 pos = q.indexOf[id];
if (pos == 0) revert BQ_EntryNotFound();
uint256 oldPacked = q.tree[pos];
if (_bidOf(oldPacked) == newBidBps) return; // same bid — early return
uint240 regNonce = _nonceOf(oldPacked);
uint256 newPacked = _pack(newBidBps, regNonce);
q.tree[pos] = newPacked;
if (newPacked > oldPacked) _siftUp(q, pos);
else _siftDown(q, pos);
}
/// Remove and return the root (highest-priority entry).
function pop(
Queue storage q
) internal returns (bytes32 id, uint16 bidBps) {
if (q.size == 0) revert BQ_EmptyQueue();
id = q.idAt[1];
bidBps = _bidOf(q.tree[1]);
remove(q, id);
}
/// Remove and return the root with its registration nonce (for reinsert).
function popFull(
Queue storage q
) internal returns (bytes32 id, uint16 bidBps, uint240 regNonce) {
if (q.size == 0) revert BQ_EmptyQueue();
id = q.idAt[1];
uint256 packed = q.tree[1];
bidBps = _bidOf(packed);
regNonce = _nonceOf(packed);
remove(q, id);
}
/// Insert with an explicit nonce (preserves FIFO position after popFull).
/// Does NOT increment the global nonce counter.
function reinsert(
Queue storage q,
bytes32 id,
uint16 bidBps,
uint240 regNonce
) internal {
if (bidBps > MAX_BID_BPS) revert BidTooHigh();
if (q.indexOf[id] != 0) revert BQ_DuplicateEntry();
uint256 packed = _pack(bidBps, regNonce);
uint256 pos = ++q.size;
q.tree[pos] = packed;
q.indexOf[id] = pos;
q.idAt[pos] = id;
_siftUp(q, pos);
}
/// Read root without mutation. O(1).
function peek(
Queue storage q
) internal view returns (bytes32 id, uint16 bidBps) {
if (q.size == 0) revert BQ_EmptyQueue();
id = q.idAt[1];
bidBps = _bidOf(q.tree[1]);
}
/// Check if an entry exists.
function contains(
Queue storage q,
bytes32 id
) internal view returns (bool) {
return q.indexOf[id] != 0;
}
/// Read the bid of an existing entry.
function bidOf(
Queue storage q,
bytes32 id
) internal view returns (uint16) {
uint256 pos = q.indexOf[id];
if (pos == 0) revert BQ_EntryNotFound();
return _bidOf(q.tree[pos]);
}
/// Read the entryId at a given heap position (1-indexed).
function entryAt(
Queue storage q,
uint256 pos
) internal view returns (bytes32) {
return q.idAt[pos];
}
// ═══════════════════════════════════════════════════════════════════════════
// Sift — hold-and-place pattern (3 writes per level instead of 6)
// ═══════════════════════════════════════════════════════════════════════════
function _siftUp(
Queue storage q,
uint256 pos
) private {
uint256 held = q.tree[pos];
bytes32 heldId = q.idAt[pos];
while (pos > 1) {
uint256 parent = pos / 2;
uint256 parentPacked = q.tree[parent];
if (held <= parentPacked) break;
// Shift parent down.
bytes32 parentId = q.idAt[parent];
q.tree[pos] = parentPacked;
q.indexOf[parentId] = pos;
q.idAt[pos] = parentId;
pos = parent;
}
// Place held element at final position.
q.tree[pos] = held;
q.indexOf[heldId] = pos;
q.idAt[pos] = heldId;
}
function _siftDown(
Queue storage q,
uint256 pos
) private {
uint256 n = q.size;
uint256 held = q.tree[pos];
bytes32 heldId = q.idAt[pos];
while (true) {
uint256 left = 2 * pos;
if (left > n) break;
uint256 right = left + 1;
uint256 largest = left;
// Pick larger child.
if (right <= n && q.tree[right] > q.tree[left]) largest = right;
uint256 childPacked = q.tree[largest];
if (held >= childPacked) break;
// Shift child up.
bytes32 childId = q.idAt[largest];
q.tree[pos] = childPacked;
q.indexOf[childId] = pos;
q.idAt[pos] = childId;
pos = largest;
}
// Place held element at final position.
q.tree[pos] = held;
q.indexOf[heldId] = pos;
q.idAt[pos] = heldId;
}
}
src/shared/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
// Role IDs (bytes32 hashes) — used by DalocHub AccessControl
bytes32 constant DEFAULT_ADMIN_ROLE = 0x00;
bytes32 constant EMITTER_ROLE = keccak256("EMITTER_ROLE");
bytes32 constant EMITTER_REGISTRAR_ROLE = keccak256("EMITTER_REGISTRAR_ROLE");
bytes32 constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// Numeric
uint256 constant BPS_SCALE = 10_000;
uint256 constant WAD = 1e18;
// BidQueue
uint16 constant MAX_BID_BPS = 1000;
// AuthorizationFlags deployment defaults
uint256 constant FLAG_TTL_BLOCKS = 14_400;
uint256 constant MAX_PROOF_AGE = 100;
// CircuitType discriminators — must match Rust `daloc_types::CircuitType` #[repr(u8)].
uint8 constant CIRCUIT_CREATION_PHASE1 = 5;
uint8 constant CIRCUIT_CREATION_PHASE2 = 6;
uint8 constant CIRCUIT_CLOSE_PHASE1 = 7;
uint8 constant CIRCUIT_CLOSE_PHASE2 = 8;
uint8 constant CIRCUIT_ENFORCEMENT_PHASE1 = 9;
uint8 constant CIRCUIT_ENFORCEMENT_PHASE2 = 10;
uint8 constant CIRCUIT_LIQUIDATION_PHASE1 = 11;
uint8 constant CIRCUIT_RESIZE_PHASE1 = 12;
uint8 constant CIRCUIT_RESIZE_PHASE2 = 13;
uint8 constant CIRCUIT_LIQUIDATION_PHASE2 = 14;
src/shared/DalocTopics.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
/// @title DalocTopics
/// @notice Centralized DalocLog topic constants for hub.emitLog event routing — zero logic, zero state.
///
/// ──────────────────────────────────────────────────────────────────────
/// SCOPE — what this library IS responsible for:
/// • Compile-time keccak256 topic constants for every DalocHub.emitLog event.
/// • Single source of truth for event topic strings — indexer, operator, and
/// all emitting contracts reference these constants.
///
/// ANTI-SCOPE — what this library MUST NEVER do:
/// • No logic — pure constants.
/// • No state.
/// • Never emit events directly — contracts call hub.emitLog with these topics.
///
/// JUSTIFICATION:
/// Centralizing topic constants ensures topic string consistency between emitting
/// contracts and the indexer's decoder. A typo in a topic string would cause the
/// indexer to silently miss events — compile-time constants prevent this.
///
/// PRODUCT SPACE — P = {VF,LF} × {Direct,Swap} × {Borrower,UndercollatMA,OvercollatMA} × {SameChain,CrossChain}:
/// Dimension-free infrastructure. Topics are used by all contracts across all
/// product space points.
///
/// REUSE:
/// Referenced by: CollateralManager, IssuedDebt, DebtIssuer, Underwriter, CuratorVault,
/// ProofExecutor, LiquidationExecutor, BaseMarginAgent, UndercollatMarginAgent,
/// OvercollatMarginAgent, UndercollatMarginAgentFactory, OvercollatMarginAgentFactory,
/// CommitmentRegistry, AuthorizationFlags, FactsRegistry, OracleAdapter.
/// ──────────────────────────────────────────────────────────────────────
library DalocTopics {
// IssuedDebt
bytes32 internal constant TOPIC_COLLATERAL_SEIZED = keccak256("CollateralSeized");
bytes32 internal constant TOPIC_COLLATERAL_PULLED = keccak256("CollateralPulled");
// Indexer decodes as CollateralReleased — topic string must match keccak256("CollateralReleased").
bytes32 internal constant TOPIC_COLLATERAL_PUSHED = keccak256("CollateralReleased");
bytes32 internal constant TOPIC_DEBT_MINTED = keccak256("DebtMinted");
bytes32 internal constant TOPIC_DEBT_CLOSED = keccak256("DebtClosed");
bytes32 internal constant TOPIC_DEBT_BURNED = keccak256("DebtBurned");
bytes32 internal constant TOPIC_DEBT_REPAID = keccak256("DebtRepaid");
bytes32 internal constant TOPIC_PRINCIPAL_PULLED = keccak256("PrincipalPulled");
// Indexer decodes as PrincipalReleased — topic string must match keccak256("PrincipalReleased").
bytes32 internal constant TOPIC_PRINCIPAL_PUSHED = keccak256("PrincipalReleased");
// DebtIssuer
bytes32 internal constant TOPIC_DEBT_ISSUED = keccak256("DebtIssued");
// Underwriter
bytes32 internal constant TOPIC_LP_REGISTERED = keccak256("LpRegistered");
bytes32 internal constant TOPIC_LP_DEREGISTERED = keccak256("LpDeregistered");
bytes32 internal constant TOPIC_CAPITAL_DRAWN = keccak256("CapitalDrawn");
bytes32 internal constant TOPIC_CAPITAL_DEPLOYMENT_COMPLETED = keccak256("CapitalDeploymentCompleted");
bytes32 internal constant TOPIC_EXPOSURE_REGISTERED = keccak256("ExposureRegistered");
bytes32 internal constant TOPIC_CAPITAL_RETURNED = keccak256("CapitalReturned");
bytes32 internal constant TOPIC_BUFFER_FUNDED = keccak256("BufferFunded");
bytes32 internal constant TOPIC_BUFFER_DRAWN = keccak256("BufferDrawn");
bytes32 internal constant TOPIC_BUFFER_RELEASED = keccak256("BufferReleased");
bytes32 internal constant TOPIC_EXPOSURE_WRITTEN_OFF = keccak256("ExposureWrittenOff");
bytes32 internal constant TOPIC_EXPOSURE_DECREASED = keccak256("ExposureDecreased");
bytes32 internal constant TOPIC_SHARES_REDEEMED = keccak256("SharesRedeemed");
// CommitmentRegistry
bytes32 internal constant TOPIC_COMMITMENT_REGISTERED = keccak256("CommitmentRegistered");
bytes32 internal constant TOPIC_COMMITMENT_REMOVED = keccak256("CommitmentRemoved");
// ProofExecutor — one Hub topic per CircuitType (phase is the topic, not a data field).
bytes32 internal constant TOPIC_CREATION_PHASE1_SETTLED = keccak256("CreationPhase1Settled");
bytes32 internal constant TOPIC_CREATION_PHASE2_SETTLED = keccak256("CreationPhase2Settled");
bytes32 internal constant TOPIC_CLOSE_PHASE1_SETTLED = keccak256("ClosePhase1Settled");
bytes32 internal constant TOPIC_CLOSE_PHASE2_SETTLED = keccak256("ClosePhase2Settled");
bytes32 internal constant TOPIC_ENFORCEMENT_PHASE1_SETTLED = keccak256("EnforcementPhase1Settled");
bytes32 internal constant TOPIC_ENFORCEMENT_PHASE2_SETTLED = keccak256("EnforcementPhase2Settled");
// FactsRegistry
bytes32 internal constant TOPIC_FACT_REGISTERED = keccak256("FactRegistered");
// AuthorizationFlags
bytes32 internal constant TOPIC_FLAG_WRITTEN = keccak256("FlagWritten");
bytes32 internal constant TOPIC_FLAG_CLEARED = keccak256("FlagCleared");
// DalocHub
bytes32 internal constant TOPIC_INTENT_CANCELLED = keccak256("IntentCancelled");
// OracleAdapter
bytes32 internal constant TOPIC_ORACLE_SYNCED = keccak256("OracleSynced");
// CollateralManager
bytes32 internal constant TOPIC_COLLATERAL_APPROVED = keccak256("CollateralApproved");
bytes32 internal constant TOPIC_CREDIT_DELEGATION_APPROVED = keccak256("CreditDelegationApproved");
// CollateralManager (permissionless)
bytes32 internal constant TOPIC_COLLATERAL_TOPPED_UP = keccak256("CollateralToppedUp");
// CollateralManagerIssuer
bytes32 internal constant TOPIC_COLLATERAL_MANAGER_DEPLOYED = keccak256("CollateralManagerDeployed");
// LiquidationExecutor
bytes32 internal constant TOPIC_LIQUIDATION_SETTLED = keccak256("LiquidationSettled");
// ProofExecutor — Liquidation Phase1/Phase2. Separate from TOPIC_LIQUIDATION_SETTLED (LE flash settle).
bytes32 internal constant TOPIC_LIQUIDATION_PHASE1_SETTLED = keccak256("LiquidationPhase1Settled");
bytes32 internal constant TOPIC_LIQUIDATION_PHASE2_SETTLED = keccak256("LiquidationPhase2Settled");
// ProofExecutor — Resize Phase1/Phase2 after permissionless repay.
bytes32 internal constant TOPIC_RESIZE_PHASE1_SETTLED = keccak256("ResizePhase1Settled");
bytes32 internal constant TOPIC_RESIZE_PHASE2_SETTLED = keccak256("ResizePhase2Settled");
// Margin agents (cross-chain custody) — the topics both flavors share. Payload
// conventions are identical per topic so the indexer keeps one decoder per topic:
// Deployed = (salt, agent, owner); Withdrawn = (agent, token, amount, to);
// AgentKeyRegistered = (agent, wallet, name).
bytes32 internal constant TOPIC_MARGIN_AGENT_DEPLOYED = keccak256("MarginAgentDeployed");
bytes32 internal constant TOPIC_MARGIN_AGENT_WITHDRAWN = keccak256("MarginAgentWithdrawn");
bytes32 internal constant TOPIC_AGENT_KEY_REGISTERED = keccak256("AgentKeyRegistered");
bytes32 internal constant TOPIC_MARGIN_AGENT_FROZEN = keccak256("MarginAgentFrozen");
// OvercollatMarginAgent only — builder-fee approval for the borrower's own HL agent
// wallet. UndercollatMarginAgent never emits this: its keys are MPC-cosigned and
// the builder relationship is not part of any proof.
bytes32 internal constant TOPIC_BUILDER_FEE_APPROVED = keccak256("BuilderFeeApproved");
// Bid updates (queue priority)
bytes32 internal constant TOPIC_LP_BID_UPDATED = keccak256("LPBidUpdated");
bytes32 internal constant TOPIC_CURATOR_BID_UPDATED = keccak256("CuratorBidUpdated");
// CuratorVault (borrower entity)
bytes32 internal constant TOPIC_CURATOR_VAULT_DEPLOYED = keccak256("CuratorVaultDeployed");
bytes32 internal constant TOPIC_CURATOR_VAULT_DEPOSITED = keccak256("CuratorVaultDeposited");
bytes32 internal constant TOPIC_CURATOR_WITHDRAWAL_REQUESTED = keccak256("CuratorWithdrawalRequested");
bytes32 internal constant TOPIC_CURATOR_WITHDRAWAL_PROCESSED = keccak256("CuratorWithdrawalProcessed");
bytes32 internal constant TOPIC_CURATOR_WITHDRAWAL_CANCELLED = keccak256("CuratorWithdrawalCancelled");
// Separate topic because entry ids start at 0 — bytes32(0) is a live entry, so the
// processed topic (which carries one) cannot double as the failed-claim event.
bytes32 internal constant TOPIC_CURATOR_FAILED_WITHDRAWAL_CLAIMED = keccak256("CuratorFailedWithdrawalClaimed");
bytes32 internal constant TOPIC_PERFORMANCE_FEE_ACCRUED = keccak256("PerformanceFeeAccrued");
}
src/shared/Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
// --- Proof lifecycle ---
/// @notice Supplied proof bytes failed verification.
error InvalidProof();
/// @notice Fact hash was already registered in FactsRegistry.
error AlreadyVerified();
/// @notice Proof or fact hash was already consumed (replay).
error AlreadyExecuted();
/// @notice Proof observation block is too old relative to the current block.
error StaleProof();
/// @notice Proof observation block is in the future.
error FutureObservationBlock();
// --- Protocol state ---
/// @notice Protocol is paused via DalocHub.
error ProtocolPaused();
/// @notice State transition is invalid for the current debt or position lifecycle.
error InvalidTransition();
/// @notice Commitment or registration entry was not found.
error NotRegistered();
// --- Debt lifecycle ---
/// @notice Debt position was already liquidated.
error AlreadyLiquidated();
/// @notice Debt position was already closed.
error AlreadyClosed();
/// @notice Witness timestamp exceeds the current block time.
error FutureTimestamp();
/// @notice Combined fee basis points exceed the allowed scale.
error FeesTooHigh();
/// @notice Position is not flagged for liquidation in AuthorizationFlags.
error NotFlagged();
/// @notice Debt is not in the required state for this operation.
error InvalidDebtState();
// --- Underwriter ---
/// @notice LP address is already registered in the bid queue.
error AlreadyRegistered();
/// @notice Caller is not registered in the LP queue.
error NotInQueue();
/// @notice LP bid queue has reached its capacity.
error QueueFull();
/// @notice Insufficient liquid USDC or LP liquidity for the requested operation.
error InsufficientLiquidity();
/// @notice LP USDC allowance is below the minimum registration threshold.
error InsufficientAllowance();
/// @notice First-loss buffer balance is insufficient.
error InsufficientBuffer();
/// @notice NAV is zero while LP shares remain outstanding.
error ZeroNavWithSupply();
// --- Oracle ---
/// @notice Normalized oracle answer is outside configured bounds.
error AnswerOutOfBounds();
/// @notice Chainlink round data is incomplete or stale.
error ChainlinkStale();
/// @notice Chainlink feed decimals exceed the supported maximum.
error FeedDecimalsTooHigh();
// --- Input validation ---
/// @notice Required address parameter is zero.
error ZeroAddress();
/// @notice Required amount parameter is zero.
error ZeroAmount();
/// @notice Block-parameter configuration value is zero.
error ZeroBlockParams();
/// @notice Oracle answer bounds are invalid.
error InvalidAnswerBounds();
// --- Circuit types ---
/// @notice Circuit type is not allowed for ProofExecutor execution.
error InvalidCircuitType();
/// @notice Caller is not DalocHub DEFAULT_ADMIN_ROLE.
error NotHubAdmin();
// --- Registry ---
/// @notice Commitment hash must be non-zero.
error ZeroHash();
/// @notice Caller is not the MockFactsRegistry registrar.
error NotFactRegistrar();
// --- Deployment ---
/// @notice USDC token address is required but missing.
error UsdcAddressRequired();
// --- Exposure ---
/// @notice Exposure was already registered for this position.
error ExposureAlreadyRegistered();
/// @notice Write-off or settle amount exceeds the per-position registered exposure.
error ExposureExceedsRegistered();
// --- BidQueue ---
/// @notice Bid exceeds MAX_BID_BPS (1000 = 10%).
error BidTooHigh();
// --- Token accounting ---
/// @notice Available principal balance is insufficient.
error InsufficientPrincipal();
/// @notice Token balance is insufficient for the requested operation.
error InsufficientBalance();
/// @notice ERC-20 balance change did not match the expected transfer amount.
error TransferMismatch();
src/shared/ProofExecutorAuth.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {ZeroAddress} from "./Errors.sol";
/// @title ProofExecutorAuth
/// @notice Access control mixin for proof-gated contracts — pure modifier, zero logic.
///
/// ──────────────────────────────────────────────────────────────────────
/// SCOPE — what this contract IS responsible for:
/// • Provide onlyProofExecutor modifier for contracts gated by ProofExecutor.
/// • ImmutableProofExecutorAuth: immutable PE address set at construction.
/// • ProofExecutorOrExecutorAuth: extends with onlyProofExecutorOrExecutor
/// modifier adding LiquidationExecutor as secondary authorized caller.
///
/// ANTI-SCOPE — what this contract MUST NEVER do:
/// • No business logic — pure access control infrastructure.
/// • No state beyond PE/LE addresses.
/// • Never duplicate modifier logic — all PE-gated contracts inherit from here.
///
/// JUSTIFICATION:
/// Centralizing the PE authority check in one inheritable base prevents modifier
/// duplication and ensures consistent access control across all downstream contracts.
/// The two-tier variant (ProofExecutorOrExecutorAuth) is necessary because the
/// LiquidationExecutor must call settle/writeOff/releaseBuffer on Underwriter and
/// CuratorVault during flash liquidation, but is not the ProofExecutor.
///
/// PRODUCT SPACE — P = {VF,LF} × {Direct,Swap} × {Borrower,UndercollatMA,OvercollatMA} × {SameChain,CrossChain}:
/// Dimension-free infrastructure. Used by all contracts across all product space points.
///
/// REUSE:
/// Inherited by: CollateralManager, IssuedDebt, DebtIssuer, Underwriter, CuratorVault,
/// LendingAdapter, UndercollatMarginAgent, UndercollatMarginAgentFactory,
/// OvercollatMarginAgentFactory. Deliberately NOT by OvercollatMarginAgent — the
/// owner-controlled flavor carries no proof-executor surface, so naming the
/// executor there would be dead authority.
/// ──────────────────────────────────────────────────────────────────────
///
/// @notice Shared auth base for contracts gated by the ProofExecutor.
/// Provides a single authority check instead of per-contract modifier duplication.
abstract contract ProofExecutorAuth {
/// @notice Caller is not the configured ProofExecutor.
error NotProofExecutor();
modifier onlyProofExecutor() {
if (msg.sender != _proofExecutorAddress()) revert NotProofExecutor();
_;
}
/// @dev Child contracts return the configured ProofExecutor address.
function _proofExecutorAddress() internal view virtual returns (address);
}
/// @notice ProofExecutorAuth with immutable executor set at construction.
abstract contract ImmutableProofExecutorAuth is ProofExecutorAuth {
address public immutable PROOF_EXECUTOR;
constructor(
address proofExecutor_
) {
if (proofExecutor_ == address(0)) revert ZeroAddress();
PROOF_EXECUTOR = proofExecutor_;
}
function _proofExecutorAddress() internal view override returns (address) {
return PROOF_EXECUTOR;
}
}
/// @notice ProofExecutorAuth extended with LiquidationExecutor for post-flash settlement.
abstract contract ProofExecutorOrExecutorAuth is ImmutableProofExecutorAuth {
/// @notice Caller is neither the ProofExecutor nor the LiquidationExecutor.
error NotProofExecutorOrExecutor();
address public immutable LIQUIDATION_EXECUTOR;
constructor(
address proofExecutor_,
address liquidationExecutor_
) ImmutableProofExecutorAuth(proofExecutor_) {
if (liquidationExecutor_ == address(0)) revert ZeroAddress();
LIQUIDATION_EXECUTOR = liquidationExecutor_;
}
modifier onlyProofExecutorOrExecutor() {
if (msg.sender != PROOF_EXECUTOR && msg.sender != LIQUIDATION_EXECUTOR) revert NotProofExecutorOrExecutor();
_;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"forge-std/=lib/forge-std/src/",
"@hyper-evm-lib/=../lib/hyper-evm-lib/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin-contracts-upgradeable/lib/forge-std/:ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"lib/openzeppelin-contracts-upgradeable/:erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts-upgradeable/:halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"lib/openzeppelin-contracts-upgradeable/:openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"lib/openzeppelin-contracts/:halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.