Verified contractPartialMIT
ProjectEscrow
Address0x90c46e3e5be35b1048cd69403d1402feed1240d8
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,273,902
- Creation transaction
- 0x050fc65769…27f34e772f
13 files
- src/ProjectEscrow.solmain47.25 KB
- vendor/openzeppelin/contracts/interfaces/IERC1967.sol637 B
- vendor/openzeppelin/contracts/interfaces/draft-IERC1822.sol882 B
- vendor/openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol1.72 KB
- vendor/openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol6.24 KB
- vendor/openzeppelin/contracts/proxy/Proxy.sol2.7 KB
- vendor/openzeppelin/contracts/proxy/beacon/IBeacon.sol473 B
- vendor/openzeppelin/contracts/proxy/utils/Initializable.sol9.28 KB
- vendor/openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol6.32 KB
- vendor/openzeppelin/contracts/utils/Address.sol6.8 KB
- vendor/openzeppelin/contracts/utils/Errors.sol896 B
- vendor/openzeppelin/contracts/utils/LowLevelCall.sol5.51 KB
- vendor/openzeppelin/contracts/utils/StorageSlot.sol4.18 KB
src/ProjectEscrow.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {ERC1967Proxy} from "../vendor/openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
import {UUPSUpgradeable} from "../vendor/openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import {Initializable} from "../vendor/openzeppelin/contracts/proxy/utils/Initializable.sol";
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function decimals() external view returns (uint8);
}
/// @dev Bounds on award-commit and unpaid-binding review periods. Wallet activation is immediate.
uint64 constant MIN_BINDING_DELAY = 0;
uint64 constant MAX_BINDING_DELAY = 30 days;
/// @dev A monthly allocation for calendar UTC month M can be committed from MONTHLY_CUTOFF_DELAY after M ends
/// until MONTHLY_CUTOFF_DELAY after the next month ends (owner decision D1: 00:00 UTC on the 4th).
uint64 constant MONTHLY_CUTOFF_DELAY = 72 hours;
/// @notice What a vault holds funds for. One owner can hold one vault per project, token and purpose, so
/// ordinary awards and private bounties never share a balance (owner decision D13).
enum Purpose {
Ordinary,
Bounty
}
/// @notice Version 5 signatures, upgradeable single-project, single-asset, single-purpose escrow for any standard ERC-20.
/// @dev A binding needs the identity authority's transaction and the destination wallet's EIP-712 signature.
/// The latest verified binding activates immediately; earlier versions never pay. An award still waits
/// bindingDelay after commitment. The owner may cancel an unpaid binding during its review window or an
/// award's commit window, subject to MAX_CANCELS_BETWEEN_PAYMENTS. Payment and cancellation may race:
/// cancellation is effective only if mined first. It cannot guarantee recovery from a compromised
/// identity authority that also controls the destination key. Factory authority rotation has no mandatory delay. Fees accrue separately, so a blocked fee recipient cannot stop payouts.
/// Anyone may deposit; deposits join one free balance that only the owner commits or refunds to itself. An
/// ordinary vault also accepts one monthly allocation per calendar month from anyone, when the owner has
/// turned it on, the identity authority signed it, and its total is within the owner's monthly cap.
/// The payout fee and the unused-fund withdrawal fee are both 2% (ceil(gross / 50)), so awarding
/// free funds to oneself costs the same as withdrawing them (#907); each fee rounds up once per award or
/// withdrawal, so splitting an amount never lowers the fee. Tokens must have exact transfers: a fee-on-transfer deposit or payout reverts. Decimals are stored for display only; amounts are
/// token base units. The factory upgrade authority may replace vault logic without a timelock.
contract ProjectEscrow is Initializable, UUPSUpgradeable {
struct Award {
uint64 actorId;
uint128 gross;
uint128 fee;
bytes32 sourceDigest;
uint64 committedAt;
bool paid;
}
/// @notice One award of a monthly allocation, in the order the allocation root was built.
struct MonthlyAward {
uint64 actorId;
uint128 gross;
bytes32 sourceDigest;
}
/// @notice V2 execution metadata for the same immutable economic allocation. Only sources not
/// funded at sourceSequence enter this tree. A concurrent manual commit makes admission stale.
struct MonthlyReservation {
bytes32 allocationDigest;
bytes32 allocationRoot;
uint128 wholeGross;
uint128 remainingGross;
uint32 count;
uint256 sourceSequence;
}
struct AllocationNode {
bytes32 hash;
uint128 total;
}
struct MonthlyReserve {
bytes32 allocationDigest;
uint128 total;
uint128 remaining;
uint32 count;
uint64 admittedAt;
}
/// @dev The latest authority binding for an actor. activatesAt records its immediate activation.
struct Binding {
address destination;
uint64 version;
bytes32 claimDigest;
uint64 activatesAt;
bool cancelled;
}
/// @notice Maximum unpaid-binding cancellations between payments. A pending factory authority
/// rotation waives this cap but does not prevent an eligible payment from executing first.
uint8 public constant MAX_CANCELS_BETWEEN_PAYMENTS = 3;
bytes32 private constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
bytes32 private constant BINDING_TYPEHASH = keccak256(
"DestinationBinding(uint64 actorId,address destination,uint64 expectedVersion,bytes32 claimDigest,uint64 expiresAt)"
);
bytes32 private constant MONTHLY_TYPEHASH = keccak256("MonthlyAllocation(uint32 period,bytes32 allocationRoot)");
bytes32 private constant MONTHLY_RESERVE_TYPEHASH = keccak256(
"MonthlyReserveV2(uint32 period,bytes32 allocationDigest,bytes32 allocationRoot,uint128 wholeGross,uint128 remainingGross,uint32 count,uint256 sourceSequence)"
);
bytes32 private constant MONTHLY_RELEASE_TYPEHASH = keccak256(
"MonthlyRelease(uint32 period,bytes32 allocationDigest,bytes32 allocationRoot,uint128 remainingGross,uint128 releasedGross)"
);
/// @dev Upper bound on s for a canonical secp256k1 signature (EIP-2).
bytes32 private constant MAX_S = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;
IERC20 public token;
/// @notice The token's decimals at vault creation, for display only. The vault never scales amounts.
uint8 public decimals;
bytes32 public projectId;
address public owner;
Purpose public purpose;
address public feeRecipient;
/// @notice The factory that created this vault and holds the identity authority in force.
EscrowFactory public factory;
uint64 public bindingDelay;
uint128 public freeBalance;
uint128 public reservedPrincipal;
uint128 public reservedFees;
uint128 public totalDeposited;
uint128 public totalPaid;
uint128 public totalPayoutFees;
uint128 public totalGrossWithdrawn;
uint128 public totalWithdrawalFees;
uint128 public accruedFees;
/// @notice The most a monthly allocation may commit in gross, and whether anyone may submit one. Only
/// the owner sets them; the owner turns monthly commitments off at any time.
uint128 public monthlyCap;
bool public monthlyEnabled;
mapping(bytes32 => Award) public awards;
mapping(bytes32 => bool) public consumedSources;
mapping(uint64 => Binding) public bindings;
/// @notice The binding version the last payment to an actor used; 0 before the first payment.
mapping(uint64 => uint64) public paidVersion;
mapping(uint64 => uint64) public lastCommittedAt;
/// @notice Cancels recorded for an actor since the actor's last payment.
mapping(uint64 => uint8) public cancelCount;
/// @notice The allocation root committed for a period (YYYYMM); zero before its one commitment.
mapping(uint32 => bytes32) public monthlyRoots;
bool private entered;
// Append-only upgrade storage. Existing awards, signatures and monthly roots keep their meaning.
uint128 public pendingMonthlyGross;
uint256 public ordinarySourceSequence;
mapping(uint32 => MonthlyReserve) public monthlyReserves;
/// @notice Gross of a period's V2 reserve that the owner returned to free balance with a signed release.
mapping(uint32 => uint128) public monthlyReleased;
error Unauthorized();
error InvalidInput();
error InsufficientFreeBalance();
error DuplicateAward();
error InvalidBinding();
error TransferFailed();
error ReentrantCall();
error WrongPurpose();
error MonthlyDisabled();
error MonthlyWindowClosed();
error MonthlyAlreadyCommitted();
error MonthlyCapExceeded();
error InvalidAttestation();
error MonthlySourceChanged();
error MonthlyLeavesPending();
error InvalidAllocationProof();
error AwardPending();
error CancelLimit();
error InvalidWalletSignature();
error MonthlyReserveChanged();
event Deposited(address indexed depositor, uint128 amount);
event AwardCommitted(bytes32 indexed id, uint64 indexed actorId, uint128 gross, uint128 fee, bytes32 sourceDigest);
event DestinationBound(
uint64 indexed actorId, address indexed destination, uint64 version, bytes32 claimDigest, uint64 activatesAt
);
event BindingCancelled(uint64 indexed actorId, uint64 version);
event FeesClaimed(address indexed feeRecipient, uint128 amount);
event Paid(
bytes32 indexed id,
uint64 indexed actorId,
address indexed destination,
uint64 version,
uint128 gross,
uint128 net,
uint128 fee
);
event UnusedWithdrawn(address indexed destination, uint128 gross, uint128 net, uint128 fee);
event MonthlyCommitmentSet(uint128 cap, bool enabled);
event MonthlyCommitted(uint32 indexed period, bytes32 allocationRoot, uint128 gross, uint256 awards);
event MonthlyReserved(
uint32 indexed period,
bytes32 allocationDigest,
bytes32 allocationRoot,
uint128 wholeGross,
uint128 remainingGross,
uint32 count,
uint256 sourceSequence
);
event MonthlyReserveReleased(
uint32 indexed period, bytes32 allocationDigest, uint128 remainingGross, uint128 releasedGross
);
modifier onlyOwner() {
if (msg.sender != owner) revert Unauthorized();
_;
}
modifier nonReentrant() {
if (entered) revert ReentrantCall();
entered = true;
_;
entered = false;
}
/// @dev Only the factory creates vaults: the deployer is the factory, and reading its authority here
/// reverts for any other deployer.
constructor() {
_disableInitializers();
}
function _authorizeUpgrade(address) internal view override {
if (msg.sender != factory.upgradeAuthority()) revert Unauthorized();
}
function initialize(
bytes32 projectId_,
IERC20 token_,
address owner_,
Purpose purpose_,
address feeRecipient_,
uint64 bindingDelay_
) external initializer {
_initialize(projectId_, token_, owner_, purpose_, feeRecipient_, bindingDelay_);
}
/// @notice Atomic ordinary-vault setup with the owner's cap and explicit opt-out.
function initializeWithMonthlyCommitment(
bytes32 projectId_,
IERC20 token_,
address owner_,
Purpose purpose_,
address feeRecipient_,
uint64 bindingDelay_,
uint128 monthlyCap_,
bool monthlyEnabled_
) external initializer {
_initialize(projectId_, token_, owner_, purpose_, feeRecipient_, bindingDelay_);
_setMonthlyCommitment(monthlyCap_, monthlyEnabled_);
}
function _initialize(
bytes32 projectId_,
IERC20 token_,
address owner_,
Purpose purpose_,
address feeRecipient_,
uint64 bindingDelay_
) private {
EscrowFactory factory_ = EscrowFactory(msg.sender);
address identityAuthority_ = factory_.identityAuthority();
// Free funds are refunded only to the owner, whoever deposited them.
if (
projectId_ == bytes32(0) || address(token_).code.length == 0 || owner_ == address(0)
|| owner_ == address(this) || feeRecipient_ == address(0) || identityAuthority_ == address(0)
|| owner_ == identityAuthority_ || feeRecipient_ == address(this) || bindingDelay_ < MIN_BINDING_DELAY
|| bindingDelay_ > MAX_BINDING_DELAY
) revert InvalidInput();
projectId = projectId_;
token = token_;
decimals = readDecimals(token_);
owner = owner_;
purpose = purpose_;
feeRecipient = feeRecipient_;
factory = factory_;
bindingDelay = bindingDelay_;
}
/// @notice The identity authority in force, held and rotated by the factory.
function identityAuthority() public view returns (address) {
return factory.identityAuthority();
}
/// @notice EIP-712 domain: the chain and this vault, so a wallet signature cannot be replayed elsewhere.
function domainSeparator() public view returns (bytes32) {
return keccak256(
abi.encode(DOMAIN_TYPEHASH, keccak256("SlopProjectEscrow"), keccak256("5"), block.chainid, address(this))
);
}
/// @notice The digest the destination wallet signs to accept a binding. Every field must match the
/// authority's call exactly.
function bindingDigest(
uint64 actorId,
address destination,
uint64 expectedVersion,
bytes32 claimDigest,
uint64 expiresAt
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator(),
keccak256(abi.encode(BINDING_TYPEHASH, actorId, destination, expectedVersion, claimDigest, expiresAt))
)
);
}
/// @notice The digest the identity authority signs to attest one month's allocation for this vault. The
/// domain binds the chain and this vault.
function monthlyDigest(uint32 period, bytes32 allocationRoot_) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
"\x19\x01", domainSeparator(), keccak256(abi.encode(MONTHLY_TYPEHASH, period, allocationRoot_))
)
);
}
function monthlyReserveVersion() external pure returns (uint8) {
return 2;
}
/// @notice A separate type in the existing domain; legacy monthly and binding signatures stay valid.
function monthlyReserveDigest(uint32 period, MonthlyReservation calldata reservation)
public
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
"\x19\x01", domainSeparator(), keccak256(abi.encode(MONTHLY_RESERVE_TYPEHASH, period, reservation))
)
);
}
/// @notice The digest the identity authority signs to state that releasedGross of a period's unsettled
/// reserve can never settle. It binds the exact remaining gross, so a leaf that settles first makes it stale.
function monthlyReleaseDigest(uint32 period, uint128 remainingGross, uint128 releasedGross)
public
view
returns (bytes32)
{
MonthlyReserve storage month = monthlyReserves[period];
return keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator(),
keccak256(
abi.encode(
MONTHLY_RELEASE_TYPEHASH,
period,
month.allocationDigest,
monthlyRoots[period],
remainingGross,
releasedGross
)
)
)
);
}
/// @notice The allocation root: a Merkle tree over the awards in order. A leaf is
/// keccak256(0x00, actorId, gross, sourceDigest) and a node is keccak256(0x01, left, right), packed; an odd
/// last node moves up unchanged. The 0x00 and 0x01 prefixes keep a node from passing as a leaf.
function allocationRoot(MonthlyAward[] calldata entries) public pure returns (bytes32) {
uint256 count = entries.length;
if (count == 0) revert InvalidInput();
bytes32[] memory level = new bytes32[](count);
for (uint256 i; i < count; ++i) {
level[i] =
keccak256(abi.encodePacked(uint8(0), entries[i].actorId, entries[i].gross, entries[i].sourceDigest));
}
while (count > 1) {
uint256 next = (count + 1) / 2;
for (uint256 i; i < next; ++i) {
uint256 left = 2 * i;
level[i] = left + 1 < count
? keccak256(abi.encodePacked(uint8(1), level[left], level[left + 1]))
: level[left];
}
count = next;
}
return level[0];
}
/// @notice When a period's allocation may be committed: from MONTHLY_CUTOFF_DELAY after the month ends
/// until MONTHLY_CUTOFF_DELAY after the next month ends. The period is YYYYMM in UTC, year 2000 to 9999.
/// Only one period is open at a time, so a stolen authority key can commit at most one cap per month.
function monthlyWindow(uint32 period) public pure returns (uint64 opensAt, uint64 closesAt) {
uint256 year = period / 100;
uint256 month = period % 100;
if (year < 2000 || year > 9999 || month == 0 || month > 12) revert InvalidInput();
(uint256 nextYear, uint256 nextMonth) = month == 12 ? (year + 1, uint256(1)) : (year, month + 1);
(uint256 afterYear, uint256 afterMonth) =
nextMonth == 12 ? (nextYear + 1, uint256(1)) : (nextYear, nextMonth + 1);
opensAt = uint64(monthStart(nextYear, nextMonth)) + MONTHLY_CUTOFF_DELAY;
closesAt = uint64(monthStart(afterYear, afterMonth)) + MONTHLY_CUTOFF_DELAY;
}
/// @dev Unix time of 00:00 UTC on the first day of a month (proleptic Gregorian, days from civil).
function monthStart(uint256 year, uint256 month) private pure returns (uint256) {
uint256 y = month <= 2 ? year - 1 : year;
uint256 era = y / 400;
uint256 yearOfEra = y - era * 400;
uint256 dayOfYear = (153 * (month > 2 ? month - 3 : month + 9) + 2) / 5;
uint256 dayOfEra = yearOfEra * 365 + yearOfEra / 4 - yearOfEra / 100 + dayOfYear;
return (era * 146097 + dayOfEra - 719468) * 1 days;
}
/// @dev Externally owned accounts only: a 65-byte canonical secp256k1 signature that recovers to the
/// expected signer. A contract wallet cannot produce one, so it cannot be bound or attest in this version.
function signedBy(bytes32 digest, address expected, bytes calldata signature) private pure returns (bool) {
if (signature.length != 65) return false;
bytes32 r = bytes32(signature[0:32]);
bytes32 s = bytes32(signature[32:64]);
uint8 v = uint8(signature[64]);
if (s > MAX_S || (v != 27 && v != 28)) return false;
address signer = ecrecover(digest, v, r, s);
return signer != address(0) && signer == expected;
}
/// @notice The only valid award ID for a source. Binding the chain and vault stops another vault from
/// claiming the same ID first.
function awardId(bytes32 sourceDigest) public view returns (bytes32) {
return keccak256(abi.encode(block.chainid, address(this), sourceDigest));
}
/// @notice The 2% fee deducted from a gross award, rounded up once per award, so splitting an award into
/// pieces under 50 base units never avoids it.
function payoutFee(uint128 gross) public pure returns (uint128) {
return gross / 50 + (gross % 50 == 0 ? 0 : 1);
}
/// @notice The fee on one unused-fund withdrawal: the same 2% as payoutFee, rounded up once per withdrawal
/// (PRD section 18, #907).
function withdrawalFee(uint128 gross) public pure returns (uint128) {
return payoutFee(gross);
}
/// @notice Every counter in one call, so a reader gets one consistent block. Equal to the public getters.
function totals()
external
view
returns (
uint128 deposited,
uint128 paid,
uint128 payoutFees,
uint128 grossWithdrawn,
uint128 withdrawalFees,
uint128 free,
uint128 principalReserved,
uint128 feesReserved,
uint128 feesAccrued,
uint256 balance
)
{
return (
totalDeposited,
totalPaid,
totalPayoutFees,
totalGrossWithdrawn,
totalWithdrawalFees,
freeBalance,
reservedPrincipal,
reservedFees,
accruedFees,
token.balanceOf(address(this))
);
}
/// @notice Anyone may deposit. The amount joins the free balance, which only the owner can commit to awards
/// or refund to itself; a depositor gets no refund right. Direct transfers are not credited.
function deposit(uint128 amount) external nonReentrant {
if (amount == 0) revert InvalidInput();
uint256 beforeBalance = token.balanceOf(address(this));
callToken(abi.encodeCall(IERC20.transferFrom, (msg.sender, address(this), amount)));
if (token.balanceOf(address(this)) != beforeBalance + amount) revert TransferFailed();
freeBalance += amount;
totalDeposited += amount;
emit Deposited(msg.sender, amount);
}
/// @param sourceDigest Unique per award origin (project/cycle/actor/allocation), not a whole-cycle digest.
function commitAward(bytes32 id, uint64 actorId, uint128 gross, bytes32 sourceDigest) external onlyOwner {
if (purpose != Purpose.Ordinary) revert WrongPurpose();
if (pendingMonthlyGross != 0) revert MonthlyLeavesPending();
commit(id, actorId, gross, sourceDigest, payoutFee(gross));
}
/// @notice Owner-approved private bounty: exactly 75% to the researcher and 25% to Slop. Only a bounty
/// vault takes it. The source must be a random opaque commitment, never a digest of a private report.
function commitBountyAward(bytes32 id, uint64 actorId, uint128 gross, bytes32 sourceDigest) external onlyOwner {
if (purpose != Purpose.Bounty) revert WrongPurpose();
if (gross % 4 != 0) revert InvalidInput();
commit(id, actorId, gross, sourceDigest, gross / 4);
}
/// @notice The owner sets the monthly cap and turns monthly commitments on or off. While they are off,
/// nobody can commit a monthly allocation; awards already committed stay committed.
function setMonthlyCommitment(uint128 cap, bool enabled) external onlyOwner {
_setMonthlyCommitment(cap, enabled);
}
function _setMonthlyCommitment(uint128 cap, bool enabled) private {
if (purpose != Purpose.Ordinary) revert WrongPurpose();
if (enabled && cap == 0) revert InvalidInput();
monthlyCap = cap;
monthlyEnabled = enabled;
emit MonthlyCommitmentSet(cap, enabled);
}
/// @notice Anyone may commit one period's allocation inside its window, once per period, while the owner
/// has monthly commitments on. The identity authority must have signed monthlyDigest(period, root) for
/// exactly these awards, and their gross total must be within monthlyCap. The free balance covers new
/// awards only; matching existing awards retain their payment state and are never reserved twice.
function commitMonthly(uint32 period, MonthlyAward[] calldata entries, bytes calldata attestation) external {
if (purpose != Purpose.Ordinary) revert WrongPurpose();
if (!monthlyEnabled) revert MonthlyDisabled();
(uint64 opensAt, uint64 closesAt) = monthlyWindow(period);
if (block.timestamp < opensAt || block.timestamp >= closesAt) revert MonthlyWindowClosed();
if (monthlyRoots[period] != bytes32(0)) revert MonthlyAlreadyCommitted();
bytes32 root = allocationRoot(entries);
if (!signedBy(monthlyDigest(period, root), factory.identityAuthority(), attestation)) {
revert InvalidAttestation();
}
uint256 total;
bool[] memory alreadyCommitted = new bool[](entries.length);
for (uint256 i; i < entries.length; ++i) {
total += entries[i].gross;
alreadyCommitted[i] = awards[awardId(entries[i].sourceDigest)].actorId != 0;
}
if (total > monthlyCap) revert MonthlyCapExceeded();
monthlyRoots[period] = root;
for (uint256 i; i < entries.length; ++i) {
MonthlyAward calldata entry = entries[i];
bytes32 id = awardId(entry.sourceDigest);
Award storage existing = awards[id];
uint128 fee = payoutFee(entry.gross);
if (alreadyCommitted[i]) {
// An owner can reserve or pay an award while this signed allocation is in transit.
// Count the exact same obligation once; a changed award must still fail closed. An
// award reserved before fees rounded up holds floor(gross / 50) and is still the same award.
if (
existing.actorId != entry.actorId || existing.gross != entry.gross
|| existing.sourceDigest != entry.sourceDigest
|| (existing.fee != fee && existing.fee != entry.gross / 50)
) revert DuplicateAward();
} else {
commit(id, entry.actorId, entry.gross, entry.sourceDigest, fee);
}
}
emit MonthlyCommitted(period, root, uint128(total), entries.length);
}
/// @notice Reserve the complete unfunded remainder in one bounded call. Leaf creation never needs
/// a wallet, fresh authority signature, an open admission window, or the owner's later opt-in.
function reserveMonthly(uint32 period, MonthlyReservation calldata reservation, bytes calldata attestation)
external
{
if (purpose != Purpose.Ordinary) revert WrongPurpose();
if (!monthlyEnabled) revert MonthlyDisabled();
(uint64 opensAt, uint64 closesAt) = monthlyWindow(period);
if (block.timestamp < opensAt || block.timestamp >= closesAt) revert MonthlyWindowClosed();
if (monthlyRoots[period] != bytes32(0)) revert MonthlyAlreadyCommitted();
if (reservation.sourceSequence != ordinarySourceSequence) revert MonthlySourceChanged();
if (
reservation.allocationDigest == bytes32(0) || reservation.allocationRoot == bytes32(0)
|| reservation.wholeGross == 0 || reservation.remainingGross > reservation.wholeGross
|| (reservation.count == 0) != (reservation.remainingGross == 0)
) revert InvalidInput();
if (reservation.wholeGross > monthlyCap) revert MonthlyCapExceeded();
if (!signedBy(monthlyReserveDigest(period, reservation), factory.identityAuthority(), attestation)) {
revert InvalidAttestation();
}
if (reservation.remainingGross > freeBalance) revert InsufficientFreeBalance();
freeBalance -= reservation.remainingGross;
pendingMonthlyGross += reservation.remainingGross;
monthlyRoots[period] = reservation.allocationRoot;
monthlyReserves[period] = MonthlyReserve(
reservation.allocationDigest,
reservation.remainingGross,
reservation.remainingGross,
reservation.count,
uint64(block.timestamp)
);
emit MonthlyReserved(
period,
reservation.allocationDigest,
reservation.allocationRoot,
reservation.wholeGross,
reservation.remainingGross,
reservation.count,
reservation.sourceSequence
);
}
/// @notice Materialize one authenticated award from its existing monthly reserve. Global source
/// consumption makes duplicate/replayed leaves fail before any accounting change.
function commitMonthlyLeaf(
uint32 period,
MonthlyAward calldata entry,
uint32 index,
AllocationNode[] calldata proof
) external {
MonthlyReserve storage month = monthlyReserves[period];
if (month.allocationDigest == bytes32(0) || index >= month.count) revert InvalidAllocationProof();
AllocationNode memory node = AllocationNode(
keccak256(abi.encodePacked(uint8(0), entry.actorId, entry.gross, entry.sourceDigest)), entry.gross
);
uint256 width = month.count;
uint256 cursor;
while (width > 1) {
if (index % 2 == 1 || index + 1 < width) {
if (cursor == proof.length) revert InvalidAllocationProof();
AllocationNode calldata sibling = proof[cursor++];
node = index % 2 == 1 ? sumNode(sibling, node) : sumNode(node, sibling);
}
index /= 2;
width = (width + 1) / 2;
}
if (
cursor != proof.length || node.hash != monthlyRoots[period] || node.total != month.total
|| entry.gross > month.remaining
) revert InvalidAllocationProof();
month.remaining -= entry.gross;
pendingMonthlyGross -= entry.gross;
// Reclassify an existing reserve. Do not charge freeBalance again.
recordAward(awardId(entry.sourceDigest), entry.actorId, entry.gross, entry.sourceDigest, payoutFee(entry.gross));
}
/// @notice The owner returns gross of a V2 reserve that can never settle (an attester fault) to free
/// balance. The identity authority in force must sign monthlyReleaseDigest for the current remaining
/// gross. Committed leaves, awards and fees do not change. Time alone never releases a reserve, and
/// the period stays committed. A leaf still proves while its gross fits the remaining reserve.
function releaseMonthlyReserve(
uint32 period,
uint128 expectedRemaining,
uint128 releasedGross,
bytes calldata attestation
) external onlyOwner {
MonthlyReserve storage month = monthlyReserves[period];
if (month.allocationDigest == bytes32(0) || releasedGross == 0) revert InvalidInput();
if (month.remaining != expectedRemaining) revert MonthlyReserveChanged();
if (releasedGross > expectedRemaining) revert InvalidInput();
if (!signedBy(
monthlyReleaseDigest(period, expectedRemaining, releasedGross), factory.identityAuthority(), attestation
)) {
revert InvalidAttestation();
}
month.remaining = expectedRemaining - releasedGross;
pendingMonthlyGross -= releasedGross;
monthlyReleased[period] += releasedGross;
freeBalance += releasedGross;
emit MonthlyReserveReleased(period, month.allocationDigest, expectedRemaining, releasedGross);
}
function sumNode(AllocationNode memory left, AllocationNode memory right)
private
pure
returns (AllocationNode memory)
{
return AllocationNode(
keccak256(abi.encodePacked(uint8(1), left.hash, left.total, right.hash, right.total)),
left.total + right.total
);
}
function commit(bytes32 id, uint64 actorId, uint128 gross, bytes32 sourceDigest, uint128 fee) private {
recordAward(id, actorId, gross, sourceDigest, fee);
if (gross > freeBalance) revert InsufficientFreeBalance();
freeBalance -= gross;
}
function recordAward(bytes32 id, uint64 actorId, uint128 gross, bytes32 sourceDigest, uint128 fee) private {
if (actorId == 0 || gross == 0 || sourceDigest == bytes32(0) || id != awardId(sourceDigest)) {
revert InvalidInput();
}
if (awards[id].actorId != 0 || consumedSources[sourceDigest]) revert DuplicateAward();
reservedPrincipal += gross - fee;
reservedFees += fee;
uint64 committedAt = uint64(block.timestamp);
awards[id] = Award(actorId, gross, fee, sourceDigest, committedAt, false);
lastCommittedAt[actorId] = committedAt;
consumedSources[sourceDigest] = true;
if (purpose == Purpose.Ordinary) ++ordinarySourceSequence;
emit AwardCommitted(id, actorId, gross, fee, sourceDigest);
}
/// @notice Direct authority transaction plus the destination wallet's EIP-712 signature over the same
/// fields; chain ID and target contract bind both. The service must verify the GitHub actor before
/// signing; the wallet signature proves the destination accepts the binding. Expiry limits submission
/// of both signatures, not claim lifetime. expectedVersion prevents stale or reordered wallet updates.
function bindDestination(
uint64 actorId,
address destination,
uint64 expectedVersion,
bytes32 claimDigest,
uint64 expiresAt,
bytes calldata walletSignature
) external {
if (msg.sender != factory.identityAuthority()) revert Unauthorized();
if (
actorId == 0 || destination == address(0) || destination == address(this) || claimDigest == bytes32(0)
|| expiresAt < block.timestamp || bindings[actorId].version != expectedVersion
) revert InvalidBinding();
if (!signedBy(
bindingDigest(actorId, destination, expectedVersion, claimDigest, expiresAt),
destination,
walletSignature
)) {
revert InvalidWalletSignature();
}
uint64 version = expectedVersion + 1;
uint64 activatesAt = uint64(block.timestamp);
bindings[actorId] = Binding(destination, version, claimDigest, activatesAt, false);
emit DestinationBound(actorId, destination, version, claimDigest, activatesAt);
}
/// @notice Cancel the latest unpaid binding during its binding or award review period. A payment
/// already mined cannot be cancelled. A new co-signed version is required after cancellation.
function cancelBinding(uint64 actorId, uint64 expectedVersion) external onlyOwner {
Binding storage binding = bindings[actorId];
if (
binding.version == 0 || binding.version != expectedVersion || binding.cancelled
|| binding.version == paidVersion[actorId]
) revert InvalidBinding();
uint64 committedAt = lastCommittedAt[actorId];
bool walletReviewWindow = block.timestamp < uint256(binding.activatesAt) + bindingDelay;
bool commitWindow = committedAt != 0 && block.timestamp < committedAt + bindingDelay;
if (!walletReviewWindow && !commitWindow) revert InvalidBinding();
if (factory.pendingIdentityAuthority() == address(0)) {
if (cancelCount[actorId] >= MAX_CANCELS_BETWEEN_PAYMENTS) revert CancelLimit();
cancelCount[actorId] += 1;
}
binding.cancelled = true;
emit BindingCancelled(actorId, expectedVersion);
}
/// @notice The binding a payment to this actor would use now: the latest verified, uncancelled binding. Version 0 means no binding can pay; an earlier binding never pays.
function payableBinding(uint64 actorId) public view returns (address destination, uint64 version) {
Binding storage binding = bindings[actorId];
if (binding.version != 0 && !binding.cancelled && block.timestamp >= binding.activatesAt) {
return (binding.destination, binding.version);
}
return (address(0), 0);
}
/// @notice Pays an award to its actor's current binding once the award's commit delay has passed. Anyone can call it, because the destination is fixed by the contract.
function pay(bytes32 id, uint64 expectedBindingVersion) external nonReentrant {
Award storage award = awards[id];
if (award.actorId == 0 || award.paid) revert InvalidInput();
if (block.timestamp < award.committedAt + bindingDelay) revert AwardPending();
(address destination, uint64 version) = payableBinding(award.actorId);
if (version == 0 || version != expectedBindingVersion) revert InvalidBinding();
paidVersion[award.actorId] = version;
cancelCount[award.actorId] = 0;
uint128 net = award.gross - award.fee;
award.paid = true;
reservedPrincipal -= net;
reservedFees -= award.fee;
totalPaid += net;
totalPayoutFees += award.fee;
accruedFees += award.fee;
sendExact(destination, net);
emit Paid(id, award.actorId, destination, version, award.gross, net, award.fee);
}
/// @notice Refunds free funds to the owner less withdrawalFee(gross), 2% rounded up, so splitting a
/// withdrawal never lowers the fee.
function withdrawUnused(uint128 gross) external onlyOwner nonReentrant {
if (gross == 0) revert InvalidInput();
if (gross > freeBalance) revert InsufficientFreeBalance();
uint128 fee = withdrawalFee(gross);
freeBalance -= gross;
totalGrossWithdrawn += gross;
totalWithdrawalFees += fee;
accruedFees += fee;
sendExact(owner, gross - fee);
emit UnusedWithdrawn(owner, gross, gross - fee, fee);
}
/// @notice Anyone can move accrued fees to the fee recipient. Only this call depends on that address.
function claimFees() external nonReentrant {
uint128 amount = accruedFees;
if (amount == 0) revert InvalidInput();
accruedFees = 0;
sendExact(feeRecipient, amount);
emit FeesClaimed(feeRecipient, amount);
}
function sendExact(address destination, uint256 amount) private {
if (amount == 0) return;
uint256 beforeVault = token.balanceOf(address(this));
uint256 beforeRecipient = token.balanceOf(destination);
callToken(abi.encodeCall(IERC20.transfer, (destination, amount)));
if (
token.balanceOf(address(this)) != beforeVault - amount
|| token.balanceOf(destination) != beforeRecipient + amount
) revert TransferFailed();
}
/// @dev decimals() is optional in ERC-20 but every supported asset has it; a token without it is rejected.
function readDecimals(IERC20 token_) private view returns (uint8) {
(bool ok, bytes memory result) = address(token_).staticcall(abi.encodeCall(IERC20.decimals, ()));
if (!ok || result.length != 32) revert InvalidInput();
uint256 value = abi.decode(result, (uint256));
if (value > type(uint8).max) revert InvalidInput();
return uint8(value);
}
function callToken(bytes memory data) private {
(bool ok, bytes memory result) = address(token).call(data);
if (!ok || (result.length != 0 && (result.length != 32 || !abi.decode(result, (bool))))) {
revert TransferFailed();
}
}
}
/// @notice Anyone creates a vault for itself: the caller is the owner, and there is one vault per (owner,
/// project ID, token, purpose) in this deployment. The token is a per-vault parameter, so one factory serves
/// every standard ERC-20 on its chain. A vault proves only who created it; the project registry decides
/// which owner's vault a project uses.
/// The registrar rotates the identity authority without a mandatory waiting period. The separate
/// upgrade authority controls factory and vault upgrades and may change logic governing deposited funds.
contract EscrowFactory is Initializable, UUPSUpgradeable {
uint64 public constant AUTHORITY_ROTATION_DELAY = 0;
address public upgradeAuthority;
address public pendingUpgradeAuthority;
address public vaultImplementation;
address public registrar;
address public feeRecipient;
uint64 public bindingDelay;
address public identityAuthority;
address public pendingIdentityAuthority;
uint64 public identityAuthorityEffectiveAt;
/// @notice The vault for vaultKey(owner, projectId, token, purpose), or zero.
mapping(bytes32 => address) public vaults;
error RotationPending();
error NoRotationPending();
error RotationNotReady();
error DuplicateVault();
event VaultCreated(
bytes32 indexed projectId,
address indexed token,
address indexed vault,
address owner,
Purpose purpose,
uint8 decimals
);
event IdentityAuthorityRotationProposed(address indexed current, address indexed proposed, uint64 effectiveAt);
event IdentityAuthorityRotationCancelled(address indexed proposed);
event IdentityAuthorityRotated(address indexed previous, address indexed current);
modifier onlyRegistrar() {
if (msg.sender != registrar) revert ProjectEscrow.Unauthorized();
_;
}
event UpgradeAuthorityProposed(address indexed authority);
event UpgradeAuthorityTransferred(address indexed previous, address indexed authority);
event VaultImplementationSet(address indexed implementation);
modifier onlyUpgradeAuthority() {
if (msg.sender != upgradeAuthority) revert ProjectEscrow.Unauthorized();
_;
}
constructor() {
_disableInitializers();
}
function _authorizeUpgrade(address) internal view override onlyUpgradeAuthority {}
function initialize(
address registrar_,
address feeRecipient_,
address identityAuthority_,
uint64 bindingDelay_,
address upgradeAuthority_,
address vaultImplementation_
) external initializer {
if (
upgradeAuthority_ == address(0) || upgradeAuthority_ == feeRecipient_
|| upgradeAuthority_ == identityAuthority_
) {
revert ProjectEscrow.InvalidInput();
}
upgradeAuthority = upgradeAuthority_;
_setVaultImplementation(vaultImplementation_);
if (
registrar_ == address(0) || feeRecipient_ == address(0) || identityAuthority_ == address(0)
|| identityAuthority_ == registrar_ || bindingDelay_ < MIN_BINDING_DELAY
|| bindingDelay_ > MAX_BINDING_DELAY
) revert ProjectEscrow.InvalidInput();
registrar = registrar_;
feeRecipient = feeRecipient_;
identityAuthority = identityAuthority_;
bindingDelay = bindingDelay_;
}
/// @notice Transfer upgrade control with recipient acceptance; no time delay applies.
function proposeUpgradeAuthority(address next) external onlyUpgradeAuthority {
if (next == address(0) || next == feeRecipient || next == identityAuthority || next == pendingIdentityAuthority)
{
revert ProjectEscrow.InvalidInput();
}
pendingUpgradeAuthority = next;
emit UpgradeAuthorityProposed(next);
}
function acceptUpgradeAuthority() external {
if (msg.sender != pendingUpgradeAuthority) revert ProjectEscrow.Unauthorized();
address previous = upgradeAuthority;
upgradeAuthority = msg.sender;
delete pendingUpgradeAuthority;
emit UpgradeAuthorityTransferred(previous, msg.sender);
}
/// @notice Select the implementation for future vaults. Existing vaults require individual upgrades.
function setVaultImplementation(address implementation_) external onlyUpgradeAuthority {
_setVaultImplementation(implementation_);
}
function _setVaultImplementation(address implementation_) private {
if (
UUPSUpgradeable(implementation_).proxiableUUID()
!= 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
) {
revert ProjectEscrow.InvalidInput();
}
vaultImplementation = implementation_;
emit VaultImplementationSet(implementation_);
}
/// @notice The mapping key and CREATE2 salt of an owner's vault for a project, token and purpose.
function vaultKey(address owner, bytes32 projectId, IERC20 token, Purpose purpose) public pure returns (bytes32) {
return keccak256(abi.encode(owner, projectId, token, purpose));
}
/// @notice Compatibility entry point: monthly commitments stay off until the owner configures them.
function create(bytes32 projectId, IERC20 token, Purpose purpose) external returns (address vault) {
return _create(
projectId,
token,
purpose,
abi.encodeCall(
ProjectEscrow.initialize, (projectId, token, msg.sender, purpose, feeRecipient, bindingDelay)
)
);
}
/// @notice Creates the caller's ordinary vault and sets its monthly policy in the same transaction.
function createWithMonthlyCommitment(bytes32 projectId, IERC20 token, uint128 cap, bool enabled)
external
returns (address vault)
{
return _create(
projectId,
token,
Purpose.Ordinary,
abi.encodeCall(
ProjectEscrow.initializeWithMonthlyCommitment,
(projectId, token, msg.sender, Purpose.Ordinary, feeRecipient, bindingDelay, cap, enabled)
)
);
}
function _create(bytes32 projectId, IERC20 token, Purpose purpose, bytes memory initialization)
private
returns (address vault)
{
bytes32 key = vaultKey(msg.sender, projectId, token, purpose);
if (vaults[key] != address(0)) revert DuplicateVault();
vault = address(new ERC1967Proxy{salt: key}(vaultImplementation, initialization));
ProjectEscrow created = ProjectEscrow(vault);
vaults[key] = vault;
emit VaultCreated(projectId, address(token), vault, msg.sender, purpose, created.decimals());
}
/// @notice Starts the public notice period for a replacement identity authority. One proposal at a time.
function proposeIdentityAuthority(address next) external onlyRegistrar {
if (
next == address(0) || next == identityAuthority || next == registrar || next == upgradeAuthority
|| next == pendingUpgradeAuthority
) revert ProjectEscrow.InvalidInput();
if (pendingIdentityAuthority != address(0)) revert RotationPending();
uint64 effectiveAt = uint64(block.timestamp) + AUTHORITY_ROTATION_DELAY;
pendingIdentityAuthority = next;
identityAuthorityEffectiveAt = effectiveAt;
emit IdentityAuthorityRotationProposed(identityAuthority, next, effectiveAt);
}
/// @notice The registrar withdraws its own pending proposal; nobody else can.
function cancelIdentityAuthorityRotation() external onlyRegistrar {
address proposed = pendingIdentityAuthority;
if (proposed == address(0)) revert NoRotationPending();
delete pendingIdentityAuthority;
delete identityAuthorityEffectiveAt;
emit IdentityAuthorityRotationCancelled(proposed);
}
/// @notice Anyone may execute a proposal once its notice period has passed. Bindings never reference
/// the authority, so every existing binding stays valid; only who may bind next changes.
function executeIdentityAuthorityRotation() external {
address next = pendingIdentityAuthority;
if (next == address(0)) revert NoRotationPending();
if (block.timestamp < identityAuthorityEffectiveAt) revert RotationNotReady();
address previous = identityAuthority;
identityAuthority = next;
delete pendingIdentityAuthority;
delete identityAuthorityEffectiveAt;
emit IdentityAuthorityRotated(previous, next);
}
}
vendor/openzeppelin/contracts/interfaces/IERC1967.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)
pragma solidity >=0.4.11;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
vendor/openzeppelin/contracts/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)
pragma solidity >=0.4.16;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
vendor/openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.22;
import {Proxy} from "../Proxy.sol";
import {ERC1967Utils} from "./ERC1967Utils.sol";
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an
* encoded function call, and allows initializing the storage of the proxy like a Solidity constructor.
*
* Requirements:
*
* - If `data` is empty, `msg.value` must be zero.
*/
constructor(address implementation, bytes memory _data) payable {
ERC1967Utils.upgradeToAndCall(implementation, _data);
}
/**
* @dev Returns the current implementation address.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function _implementation() internal view virtual override returns (address) {
return ERC1967Utils.getImplementation();
}
}
vendor/openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.21;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
vendor/openzeppelin/contracts/proxy/Proxy.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/Proxy.sol)
pragma solidity ^0.8.20;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0x00, 0x00, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0x00, calldatasize(), 0x00, 0x00)
// Copy the returned data.
returndatacopy(0x00, 0x00, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0x00, returndatasize())
}
default {
return(0x00, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overridden so it returns the address to which the fallback
* function and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internal call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
}
vendor/openzeppelin/contracts/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)
pragma solidity >=0.4.16;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
vendor/openzeppelin/contracts/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 reinitialization) 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 Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
vendor/openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* @custom:stateless
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
vendor/openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.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);
}
if (LowLevelCall.callNoReturn(recipient, amount, "")) {
// call successful, nothing to do
return;
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
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 = LowLevelCall.callNoReturn(target, value, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @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 = LowLevelCall.staticcallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @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 = LowLevelCall.delegatecallNoReturn(target, data);
if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
return LowLevelCall.returnData();
} else if (success) {
revert AddressEmptyCode(target);
} else if (LowLevelCall.returnDataSize() > 0) {
LowLevelCall.bubbleRevert();
} else {
revert Errors.FailedCall();
}
}
/**
* @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.
*
* NOTE: This function is DEPRECATED and may be removed in the next major release.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
// 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 (success && (returndata.length > 0 || target.code.length > 0)) {
return returndata;
} else if (success) {
revert AddressEmptyCode(target);
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
/**
* @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) {
return returndata;
} else if (returndata.length > 0) {
LowLevelCall.bubbleRevert(returndata);
} else {
revert Errors.FailedCall();
}
}
}
vendor/openzeppelin/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);
}
vendor/openzeppelin/contracts/utils/LowLevelCall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn}, but allows to specify the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturnBytes32Pair}, but allows to specify the value to be sent in the call.
function callReturn64Bytes(
address target,
uint256 value,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(
address target,
bytes memory data
) internal view returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
vendor/openzeppelin/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.