Verified contractPartialMIT
ArcadeScores
Address0xdfa5fb3727e417015d6fefacee0144c85626c667
- Balance
0 ETH
- Transactions
15
- Compiler
solc 0.8.35
- Same code
Only this contract
Details
- Compiler
- solc 0.8.35+commit.47b9dedd
- 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,377,363
- Creation transaction
- 0xeaf327a24b…1b5d87ece5
4 files
src/ArcadeScores.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.28;
import { Ownable } from "solady/auth/Ownable.sol";
import { EIP712 } from "solady/utils/EIP712.sol";
import { ECDSA } from "solady/utils/ECDSA.sol";
interface IArcadeNFTLike {
function ownerOf(uint256 tokenId) external view returns (address);
function notify(uint256 tokenId) external;
}
interface IArcadeIdentityLike {
function gameOf(uint256 tokenId) external view returns (bool revealed, uint8 game);
}
/**
* @title ArcadeScores — verified personal bests, kept by the token
* @notice A score is accepted when a verifier has RE-RUN the session (the replay of every tick's
* buttons through the same deterministic rules the token plays) and signed an EIP-712
* attestation of the result. Anyone may submit it — the player, or a sponsor paying gas —
* but only while the attested player still holds the token, only once per session ticket,
* and only if it beats the token's own best.
*
* Eleven boards: 0–9 are the ten games (a token scores only on its own game's board, which
* ArcadeIdentity knows once the collection is revealed) and 10 is the Arcade Gauntlet, open
* to all 10,000.
*
* Each board keeps its top 100 on chain, sorted, so a token's standing — Unranked, Ranked,
* Top 100, Top 10, Champion — and its permanent milestones (first score, first Top 100,
* first Top 10, first championship, time as champion) are facts of this contract, not of
* an indexer. Exact ranks below 100 are left to the public indexer.
*
* Every accepted best is kept in the token's history and emitted as an event. The replay
* bytes may ride along as calldata (their keccak must equal the attested replay hash), so a
* record can be re-verified from chain data alone, forever.
*/
contract ArcadeScores is Ownable, EIP712 {
uint256 public constant GAUNTLET = 10;
uint256 public constant TOP = 100;
uint256 internal constant SLOTS = 34; // 3 entries of 80 bits per slot
uint64 internal constant MAX_SCORE = (1 << 40) - 1;
uint8 public constant VERIFIED = 1;
uint8 public constant REVOKED = 2;
// standing, as reported by statusOf
uint8 public constant UNRANKED = 0;
uint8 public constant RANKED = 1;
uint8 public constant TOP_100 = 2;
uint8 public constant TOP_10 = 3;
uint8 public constant CHAMPION = 4;
bytes32 public constant ATTESTATION_TYPEHASH = keccak256(
"Attestation(uint8 board,uint256 tokenId,uint64 score,address player,bytes32 replayHash,uint16 ruleset,bytes32 ticket,uint64 deadline)"
);
struct Attestation {
uint8 board;
uint256 tokenId;
uint64 score;
address player;
bytes32 replayHash;
uint16 ruleset;
bytes32 ticket;
uint64 deadline;
}
struct Record {
uint64 score;
uint32 time;
uint32 seq;
uint16 ruleset;
uint8 status;
address player;
bytes32 replayHash;
}
struct Milestones {
uint32 firstScoreAt;
uint32 firstTop100At;
uint32 firstTop10At;
uint32 firstChampionAt;
uint32 championSeconds; // completed reigns; a current reign is added by `milestonesOf`
uint32 longestReign;
uint16 bestRank; // best position ever held in the top 100 (1 = champion), 0 if never
}
IArcadeNFTLike public immutable nft;
IArcadeIdentityLike public immutable identity;
uint32 public seq;
mapping(address => bool) public isVerifier;
mapping(uint256 => mapping(uint16 => bool)) public rulesetAccepted; // board => ruleset => ok
mapping(bytes32 => bool) public usedTicket;
mapping(uint256 => mapping(uint256 => Record[])) internal _history; // board => token => records
mapping(uint256 => mapping(uint256 => uint256)) internal _bestPlusOne; // board => token => index+1
mapping(uint256 => mapping(uint256 => Milestones)) internal _milestones;
mapping(uint256 => uint256[SLOTS]) internal _top; // board => packed sorted top 100
mapping(uint256 => uint256) public topCount;
mapping(uint256 => uint32) public championSince;
event PersonalBest(
uint256 indexed board,
uint256 indexed tokenId,
address indexed player,
uint256 score,
bytes32 replayHash,
uint16 ruleset,
uint256 rank,
uint256 index
);
event Milestone(uint256 indexed board, uint256 indexed tokenId, uint8 kind, uint256 when);
event ChampionChanged(uint256 indexed board, uint256 indexed tokenId, uint256 previous, uint256 when);
event Revoked(uint256 indexed board, uint256 indexed tokenId, uint256 index, string reason);
event Restored(uint256 indexed board, uint256 indexed tokenId, uint256 index);
event VerifierSet(address indexed verifier, bool allowed);
event RulesetSet(uint256 indexed board, uint16 ruleset, bool accepted);
event Executed(address indexed target, uint256 value, bytes data);
error BadBoard();
error WrongGame();
error Expired();
error RulesetNotAccepted();
error TicketUsed();
error NotOwner();
error ReplayMismatch();
error BadSignature();
error NotAPersonalBest();
error ScoreTooLarge();
error NothingToRevoke();
error BadIndex();
error CallFailed();
error NotAllowed();
error NotRevealed();
error ZeroAddress();
error NotAContract();
constructor(address owner_, address nft_, address identity_) {
if (owner_ == address(0) || nft_ == address(0) || identity_ == address(0)) revert ZeroAddress();
if (nft_.code.length == 0 || identity_.code.length == 0) revert NotAContract();
_initializeOwner(owner_);
nft = IArcadeNFTLike(nft_);
identity = IArcadeIdentityLike(identity_);
}
function _domainNameAndVersion() internal pure override returns (string memory, string memory) {
return ("The Arcade", "1");
}
function renounceOwnership() public payable override onlyOwner {
revert NotAllowed();
}
function domainSeparator() external view returns (bytes32) {
return _domainSeparator();
}
function digest(Attestation calldata a) public view returns (bytes32) {
return _hashTypedData(
keccak256(
abi.encode(
ATTESTATION_TYPEHASH, a.board, a.tokenId, a.score, a.player, a.replayHash, a.ruleset, a.ticket, a.deadline
)
)
);
}
// ───────────────────────────── record ─────────────────────────────
/**
* @param a what the verifier attests the replay scored
* @param signature the verifier's EIP-712 signature over `a`
* @param replay optional: the replay bytes themselves (kept in calldata, hash-checked)
* @return rank 1..100 if the best now stands in the board's top 100, else 0
*/
function record(Attestation calldata a, bytes calldata signature, bytes calldata replay)
external
returns (uint256 rank)
{
if (a.board > GAUNTLET) revert BadBoard();
(bool revealed, uint8 game) = identity.gameOf(a.tokenId);
if (!revealed || a.tokenId > type(uint16).max) revert NotRevealed();
if (a.board < GAUNTLET && game != a.board) revert WrongGame();
if (block.timestamp > a.deadline) revert Expired();
if (!rulesetAccepted[a.board][a.ruleset]) revert RulesetNotAccepted();
if (usedTicket[a.ticket]) revert TicketUsed();
if (nft.ownerOf(a.tokenId) != a.player) revert NotOwner();
if (replay.length != 0 && keccak256(replay) != a.replayHash) revert ReplayMismatch();
if (!isVerifier[ECDSA.recoverCalldata(digest(a), signature)]) revert BadSignature();
if (a.score > MAX_SCORE) revert ScoreTooLarge();
if (a.score <= _bestScore(a.board, a.tokenId)) revert NotAPersonalBest();
usedTicket[a.ticket] = true;
uint32 s = ++seq;
Record[] storage h = _history[a.board][a.tokenId];
h.push(Record(a.score, uint32(block.timestamp), s, a.ruleset, VERIFIED, a.player, a.replayHash));
_bestPlusOne[a.board][a.tokenId] = h.length;
rank = _place(a.board, a.tokenId, _key(a.score, s));
emit PersonalBest(a.board, a.tokenId, a.player, a.score, a.replayHash, a.ruleset, rank, h.length - 1);
}
// ───────────────────────────── the top 100 ─────────────────────────────
/// @dev Higher is better: the score, then the earlier record (a tie goes to whoever got there first).
function _key(uint64 score, uint32 s) internal pure returns (uint64) {
uint64 inv = s >= 0xFFFFFF ? 0 : uint64(0xFFFFFF - s);
return (score << 24) | inv;
}
function _load(uint256 board) internal view returns (uint16[] memory ids, uint64[] memory keys, uint256 n) {
n = topCount[board];
ids = new uint16[](TOP + 1);
keys = new uint64[](TOP + 1);
uint256[SLOTS] storage t = _top[board];
for (uint256 i; i < n; ++i) {
uint256 e = (t[i / 3] >> ((i % 3) * 80)) & ((1 << 80) - 1);
ids[i] = uint16(e >> 64);
keys[i] = uint64(e);
}
}
function _store(uint256 board, uint16[] memory ids, uint64[] memory keys, uint256 n) internal {
uint256[SLOTS] storage t = _top[board];
uint256 used = (n + 2) / 3;
uint256 old = (topCount[board] + 2) / 3;
for (uint256 j; j < (used > old ? used : old); ++j) {
uint256 w;
for (uint256 k; k < 3; ++k) {
uint256 i = j * 3 + k;
if (i < n) w |= ((uint256(ids[i]) << 64) | keys[i]) << (k * 80);
}
if (t[j] != w) t[j] = w;
}
topCount[board] = n;
}
/**
* @dev Put a token's new key into the board's top 100 (removing its old entry first) and
* settle everything that follows from where it lands: milestones, the champion's reign,
* and an ERC-4906 nudge for every token whose standing changed.
*/
function _place(uint256 board, uint256 tokenId, uint64 key) internal returns (uint256 rank) {
(uint16[] memory ids, uint64[] memory keys, uint256 n) = _load(board);
uint16 id = uint16(tokenId);
uint256 prevChampion = n > 0 ? ids[0] : 0;
uint256 was = TOP; // previous position, TOP = absent
for (uint256 i; i < n; ++i) {
if (ids[i] == id) {
was = i;
for (uint256 j = i; j + 1 < n; ++j) (ids[j], keys[j]) = (ids[j + 1], keys[j + 1]);
--n;
break;
}
}
uint256 pos = n;
for (uint256 i; i < n; ++i) {
if (key > keys[i]) {
pos = i;
break;
}
}
uint256 droppedOut; // a token pushed out of the top 100
if (pos < TOP) {
for (uint256 j = n; j > pos; --j) (ids[j], keys[j]) = (ids[j - 1], keys[j - 1]);
ids[pos] = id;
keys[pos] = key;
++n;
if (n > TOP) {
droppedOut = ids[TOP];
n = TOP;
}
rank = pos + 1;
}
_store(board, ids, keys, n);
uint32 now_ = uint32(block.timestamp);
Milestones storage m = _milestones[board][tokenId];
if (m.firstScoreAt == 0) _mark(board, tokenId, 0, now_, m);
if (rank != 0) {
if (m.bestRank == 0 || rank < m.bestRank) m.bestRank = uint16(rank);
if (m.firstTop100At == 0) _mark(board, tokenId, 1, now_, m);
if (rank <= 10 && m.firstTop10At == 0) _mark(board, tokenId, 2, now_, m);
}
if (rank == 1 && prevChampion != tokenId) {
if (prevChampion != 0) _endReign(board, prevChampion, now_, true);
championSince[board] = now_;
if (m.firstChampionAt == 0) _mark(board, tokenId, 3, now_, m);
emit ChampionChanged(board, tokenId, prevChampion, now_);
}
_notify(tokenId);
if (rank == 1 && prevChampion != 0 && prevChampion != tokenId) _notify(prevChampion);
// whoever slid from 10th to 11th (only if this token came from outside the top 10)
if (rank != 0 && rank <= 10 && was >= 10 && n > 10 && ids[10] != prevChampion) _notify(ids[10]);
if (droppedOut != 0) _notify(droppedOut);
}
function _mark(uint256 board, uint256 tokenId, uint8 kind, uint32 when, Milestones storage m) internal {
if (kind == 0) m.firstScoreAt = when;
else if (kind == 1) m.firstTop100At = when;
else if (kind == 2) m.firstTop10At = when;
else m.firstChampionAt = when;
emit Milestone(board, tokenId, kind, when);
}
function _endReign(uint256 board, uint256 tokenId, uint32 when, bool credit) internal {
if (!credit) return;
uint32 reign = when - championSince[board];
Milestones storage p = _milestones[board][tokenId];
p.championSeconds += reign;
if (reign > p.longestReign) p.longestReign = reign;
}
function _notify(uint256 tokenId) internal {
// A notifier that is unset or broken must never block a record.
try nft.notify(tokenId) { } catch { }
}
// ───────────────────────────── undo (owner) ─────────────────────────────
/**
* @notice Withdraw a token's current best (e.g. a replay later shown to exploit a rules bug).
* Its previous valid best, if any, becomes current again. The record stays in history,
* marked revoked. Milestones already earned are kept; a revoked champion's current reign
* is not credited. Tokens below the top 100 can be re-admitted with `sync`.
*/
function revoke(uint256 board, uint256 tokenId, string calldata reason) external onlyOwner {
uint256 b = _bestPlusOne[board][tokenId];
if (b == 0) revert NothingToRevoke();
Record[] storage h = _history[board][tokenId];
h[b - 1].status = REVOKED;
emit Revoked(board, tokenId, b - 1, reason);
// The current best is always the highest valid record. After a restore, a valid record can
// sit later in history than the current one, so scan all of it (audit: a backward-only scan
// orphaned such a record and let a lower score pass as a personal best).
uint256 prev;
uint64 top_;
for (uint256 i; i < h.length; ++i) {
if (h[i].status == VERIFIED && h[i].score > top_) {
top_ = h[i].score;
prev = i + 1;
}
}
_bestPlusOne[board][tokenId] = prev;
_remove(board, tokenId, false);
if (prev != 0) _place(board, tokenId, _key(h[prev - 1].score, h[prev - 1].seq));
}
/// @notice The undo for `revoke`: a record becomes valid again; if it is now the token's
/// highest valid record it becomes current and re-enters the top 100.
function restore(uint256 board, uint256 tokenId, uint256 index) external onlyOwner {
Record[] storage h = _history[board][tokenId];
if (index >= h.length || h[index].status != REVOKED) revert BadIndex();
h[index].status = VERIFIED;
emit Restored(board, tokenId, index);
uint256 b = _bestPlusOne[board][tokenId];
if (b == 0 || h[index].score > h[b - 1].score) {
_bestPlusOne[board][tokenId] = index + 1;
_remove(board, tokenId, true);
_place(board, tokenId, _key(h[index].score, h[index].seq));
}
}
/// @notice Permissionless repair: put a token's current valid best back into the top 100 if it
/// belongs there (after revocations shrink the list). Changes nothing otherwise.
function sync(uint256 board, uint256 tokenId) external returns (uint256 rank) {
uint256 b = _bestPlusOne[board][tokenId];
if (b == 0) return 0;
Record storage r = _history[board][tokenId][b - 1];
(uint16[] memory ids,, uint256 n) = _load(board);
for (uint256 i; i < n; ++i) if (ids[i] == tokenId) return i + 1;
return _place(board, tokenId, _key(r.score, r.seq));
}
function _remove(uint256 board, uint256 tokenId, bool creditReign) internal {
(uint16[] memory ids, uint64[] memory keys, uint256 n) = _load(board);
for (uint256 i; i < n; ++i) {
if (ids[i] != tokenId) continue;
for (uint256 j = i; j + 1 < n; ++j) (ids[j], keys[j]) = (ids[j + 1], keys[j + 1]);
--n;
_store(board, ids, keys, n);
if (i < 10 && n >= 10) _notify(ids[9]); // pulled up into the top 10
if (i == 0) {
uint32 now_ = uint32(block.timestamp);
_endReign(board, tokenId, now_, creditReign);
championSince[board] = now_;
if (n > 0) {
Milestones storage m = _milestones[board][ids[0]];
if (m.firstChampionAt == 0) _mark(board, ids[0], 3, now_, m);
m.bestRank = 1;
_notify(ids[0]);
}
emit ChampionChanged(board, n > 0 ? ids[0] : 0, tokenId, now_);
}
_notify(tokenId);
return;
}
}
function setVerifier(address verifier, bool allowed) external onlyOwner {
isVerifier[verifier] = allowed;
emit VerifierSet(verifier, allowed);
}
function setRuleset(uint256 board, uint16 ruleset, bool accepted) external onlyOwner {
if (board > GAUNTLET) revert BadBoard();
rulesetAccepted[board][ruleset] = accepted;
emit RulesetSet(board, ruleset, accepted);
}
function execute(address target, uint256 value, bytes calldata data) external payable onlyOwner returns (bytes memory) {
(bool ok, bytes memory ret) = target.call{ value: value }(data);
if (!ok) revert CallFailed();
emit Executed(target, value, data);
return ret;
}
// ───────────────────────────── reads ─────────────────────────────
function _bestScore(uint256 board, uint256 tokenId) internal view returns (uint64) {
uint256 b = _bestPlusOne[board][tokenId];
return b == 0 ? 0 : _history[board][tokenId][b - 1].score;
}
/// @notice The token's current valid best on a board (`found` false if it has none).
function bestOf(uint256 board, uint256 tokenId) external view returns (bool found, Record memory r, uint256 index) {
uint256 b = _bestPlusOne[board][tokenId];
if (b == 0) return (false, r, 0);
return (true, _history[board][tokenId][b - 1], b - 1);
}
function historyLength(uint256 board, uint256 tokenId) external view returns (uint256) {
return _history[board][tokenId].length;
}
function historyAt(uint256 board, uint256 tokenId, uint256 index) external view returns (Record memory) {
return _history[board][tokenId][index];
}
/// @notice 1..100 if in the board's top 100, else 0.
function rankOf(uint256 board, uint256 tokenId) public view returns (uint256) {
(uint16[] memory ids,, uint256 n) = _load(board);
for (uint256 i; i < n; ++i) if (ids[i] == tokenId) return i + 1;
return 0;
}
/**
* @notice How many tokens in ids [fromId, toId] stand above `tokenId` on `board` (better score,
* or the same score recorded earlier). The exact rank is 1 + the sum over all ids. A
* game's tokens are spread over all 10,000 ids (the reveal permutes them), so split the
* id space into a few calls (~3.4M gas per 1,500 ids).
*/
function above(uint256 board, uint256 tokenId, uint256 fromId, uint256 toId) external view returns (uint256 count) {
uint256 b = _bestPlusOne[board][tokenId];
if (b == 0) return type(uint256).max;
Record storage me = _history[board][tokenId][b - 1];
uint64 mine = _key(me.score, me.seq);
for (uint256 id = fromId; id <= toId; ++id) {
uint256 o = _bestPlusOne[board][id];
if (o == 0 || id == tokenId) continue;
Record storage r = _history[board][id][o - 1];
if (_key(r.score, r.seq) > mine) ++count;
}
}
/// @notice Unranked (no valid best) · Ranked · Top 100 · Top 10 · Champion.
function statusOf(uint256 board, uint256 tokenId) public view returns (uint8) {
if (_bestPlusOne[board][tokenId] == 0) return UNRANKED;
uint256 r = rankOf(board, tokenId);
if (r == 0) return RANKED;
if (r == 1) return CHAMPION;
if (r <= 10) return TOP_10;
return TOP_100;
}
function champion(uint256 board) external view returns (uint256 tokenId, uint32 since) {
if (topCount[board] == 0) return (0, 0);
return (uint16(_top[board][0] >> 64), championSince[board]);
}
/// @notice Milestones, with a reigning champion's current reign included.
function milestonesOf(uint256 board, uint256 tokenId) external view returns (Milestones memory m) {
m = _milestones[board][tokenId];
if (topCount[board] > 0 && uint16(_top[board][0] >> 64) == tokenId) {
uint32 cur = uint32(block.timestamp) - championSince[board];
m.championSeconds += cur;
if (cur > m.longestReign) m.longestReign = cur;
}
}
/// @notice The board's top `count` (≤ 100): token ids and scores, best first.
function top(uint256 board, uint256 count) external view returns (uint256[] memory tokenIds, uint256[] memory scores) {
(uint16[] memory ids, uint64[] memory keys, uint256 n) = _load(board);
if (count > n) count = n;
tokenIds = new uint256[](count);
scores = new uint256[](count);
for (uint256 i; i < count; ++i) {
tokenIds[i] = ids[i];
scores[i] = keys[i] >> 24;
}
}
}
../operations/lib/solady/src/auth/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
../operations/lib/solady/src/utils/ECDSA.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Gas optimized ECDSA wrapper.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ECDSA.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ECDSA.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol)
///
/// @dev Note:
/// - The recovery functions use the ecrecover precompile (0x1).
/// - As of Solady version 0.0.68, the `recover` variants will revert upon recovery failure.
/// This is for more safety by default.
/// Use the `tryRecover` variants if you need to get the zero address back
/// upon recovery failure instead.
/// - As of Solady version 0.0.134, all `bytes signature` variants accept both
/// regular 65-byte `(r, s, v)` and EIP-2098 `(r, vs)` short form signatures.
/// See: https://eips.ethereum.org/EIPS/eip-2098
/// This is for calldata efficiency on smart accounts prevalent on L2s.
///
/// WARNING! Do NOT directly use signatures as unique identifiers:
/// - The recovery operations do NOT check if a signature is non-malleable.
/// - Use a nonce in the digest to prevent replay attacks on the same contract.
/// - Use EIP-712 for the digest to prevent replay attacks across different chains and contracts.
/// EIP-712 also enables readable signing of typed data for better user safety.
/// - If you need a unique hash from a signature, please use the `canonicalHash` functions.
library ECDSA {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The order of the secp256k1 elliptic curve.
uint256 internal constant N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141;
/// @dev `N/2 + 1`. Used for checking the malleability of the signature.
uint256 private constant _HALF_N_PLUS_1 =
0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The signature is invalid.
error InvalidSignature();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RECOVERY OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function recover(bytes32 hash, bytes memory signature) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
} {
switch mload(signature)
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { continue }
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if returndatasize() { break }
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function recoverCalldata(bytes32 hash, bytes calldata signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
} {
switch signature.length
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // Copy `r` and `s`.
}
default { continue }
mstore(0x00, hash)
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if returndatasize() { break }
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the EIP-2098 short form signature defined by `r` and `vs`.
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r)
mstore(0x60, shr(1, shl(1, vs))) // `s`.
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(returndatasize()) {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the signature defined by `v`, `r`, `s`.
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, and(v, 0xff))
mstore(0x40, r)
mstore(0x60, s)
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(returndatasize()) {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* TRY-RECOVER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// WARNING!
// These functions will NOT revert upon recovery failure.
// Instead, they will return the zero address upon recovery failure.
// It is critical that the returned address is NEVER compared against
// a zero address (e.g. an uninitialized address variable).
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function tryRecover(bytes32 hash, bytes memory signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {} {
switch mload(signature)
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function tryRecoverCalldata(bytes32 hash, bytes calldata signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {} {
switch signature.length
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // Copy `r` and `s`.
}
default { break }
mstore(0x00, hash)
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the EIP-2098 short form signature defined by `r` and `vs`.
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r)
mstore(0x60, shr(1, shl(1, vs))) // `s`.
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the signature defined by `v`, `r`, `s`.
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, and(v, 0xff))
mstore(0x40, r)
mstore(0x60, s)
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an Ethereum Signed Message, created from a `hash`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign)
/// JSON-RPC method as part of EIP-191.
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, hash) // Store into scratch space for keccak256.
mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") // 28 bytes.
result := keccak256(0x04, 0x3c) // `32 * 2 - (32 - 28) = 60 = 0x3c`.
}
}
/// @dev Returns an Ethereum Signed Message, created from `s`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign)
/// JSON-RPC method as part of EIP-191.
/// Note: Supports lengths of `s` up to 999999 bytes.
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let sLength := mload(s)
let o := 0x20
mstore(o, "\x19Ethereum Signed Message:\n") // 26 bytes, zero-right-padded.
mstore(0x00, 0x00)
// Convert the `s.length` to ASCII decimal representation: `base10(s.length)`.
for { let temp := sLength } 1 {} {
o := sub(o, 1)
mstore8(o, add(48, mod(temp, 10)))
temp := div(temp, 10)
if iszero(temp) { break }
}
let n := sub(0x3a, o) // Header length: `26 + 32 - o`.
// Throw an out-of-offset error (consumes all gas) if the header exceeds 32 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0x20))
mstore(s, or(mload(0x00), mload(n))) // Temporarily store the header.
result := keccak256(add(s, sub(0x20, n)), add(n, sLength))
mstore(s, sLength) // Restore the length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CANONICAL HASH FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// The following functions return the hash of the signature in its canonicalized format,
// which is the 65-byte `abi.encodePacked(r, s, uint8(v))`, where `v` is either 27 or 28.
// If `s` is greater than `N / 2` then it will be converted to `N - s`
// and the `v` value will be flipped.
// If the signature has an invalid length, or if `v` is invalid,
// a uniquely corrupt hash will be returned.
// These functions are useful for "poor-mans-VRF".
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(bytes memory signature) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let l := mload(signature)
for {} 1 {} {
mstore(0x00, mload(add(signature, 0x20))) // `r`.
let s := mload(add(signature, 0x40))
let v := mload(add(signature, 0x41))
if eq(l, 64) {
v := add(shr(255, s), 27)
s := shr(1, shl(1, s))
}
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
break
}
// If the length is neither 64 nor 65, return a uniquely corrupted hash.
if iszero(lt(sub(l, 64), 2)) {
// `bytes4(keccak256("InvalidSignatureLength"))`.
result := xor(keccak256(add(signature, 0x20), l), 0xd62f1ab2)
}
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHashCalldata(bytes calldata signature)
internal
pure
returns (bytes32 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
mstore(0x00, calldataload(signature.offset)) // `r`.
let s := calldataload(add(signature.offset, 0x20))
let v := calldataload(add(signature.offset, 0x21))
if eq(signature.length, 64) {
v := add(shr(255, s), 27)
s := shr(1, shl(1, s))
}
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
break
}
// If the length is neither 64 nor 65, return a uniquely corrupted hash.
if iszero(lt(sub(signature.length, 64), 2)) {
calldatacopy(mload(0x40), signature.offset, signature.length)
// `bytes4(keccak256("InvalidSignatureLength"))`.
result := xor(keccak256(mload(0x40), signature.length), 0xd62f1ab2)
}
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(bytes32 r, bytes32 vs) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, r) // `r`.
let v := add(shr(255, vs), 27)
let s := shr(1, shl(1, vs))
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(uint8 v, bytes32 r, bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, r) // `r`.
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EMPTY CALLDATA HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an empty calldata bytes.
function emptySignature() internal pure returns (bytes calldata signature) {
/// @solidity memory-safe-assembly
assembly {
signature.length := 0
}
}
}
../operations/lib/solady/src/utils/EIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Contract for EIP-712 typed structured data hashing and signing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/EIP712.sol)
/// @author Modified from Solbase (https://github.com/Sol-DAO/solbase/blob/main/src/utils/EIP712.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/EIP712.sol)
///
/// @dev Note, this implementation:
/// - Uses `address(this)` for the `verifyingContract` field.
/// - Does NOT use the optional EIP-712 salt.
/// - Does NOT use any EIP-712 extensions.
/// This is for simplicity and to save gas.
/// If you need to customize, please fork / modify accordingly.
abstract contract EIP712 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS AND IMMUTABLES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 internal constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("EIP712Domain(string name,string version,address verifyingContract)")`.
/// This is only used in `_hashTypedDataSansChainId`.
bytes32 internal constant _DOMAIN_TYPEHASH_SANS_CHAIN_ID =
0x91ab3d17e3a50a9d89e63fd30b92be7f5336b03b287bb946787a83a9d62a2766;
/// @dev `keccak256("EIP712Domain(string name,string version)")`.
/// This is only used in `_hashTypedDataSansChainIdAndVerifyingContract`.
bytes32 internal constant _DOMAIN_TYPEHASH_SANS_CHAIN_ID_AND_VERIFYING_CONTRACT =
0xb03948446334eb9b2196d5eb166f69b9d49403eb4a12f36de8d3f9f3cb8e15c3;
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId)")`.
/// This is only used in `_hashTypedDataSansVerifyingContract`.
bytes32 internal constant _DOMAIN_TYPEHASH_SANS_VERIFYING_CONTRACT =
0xc2f8787176b8ac6bf7215b4adcc1e069bf4ab82d9ab1df05a57a91d425935b6e;
uint256 private immutable _cachedThis;
uint256 private immutable _cachedChainId;
bytes32 private immutable _cachedNameHash;
bytes32 private immutable _cachedVersionHash;
bytes32 private immutable _cachedDomainSeparator;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTRUCTOR */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Cache the hashes for cheaper runtime gas costs.
/// In the case of upgradeable contracts (i.e. proxies),
/// or if the chain id changes due to a hard fork,
/// the domain separator will be seamlessly calculated on-the-fly.
constructor() {
_cachedThis = uint256(uint160(address(this)));
_cachedChainId = block.chainid;
string memory name;
string memory version;
if (!_domainNameAndVersionMayChange()) (name, version) = _domainNameAndVersion();
bytes32 nameHash = _domainNameAndVersionMayChange() ? bytes32(0) : keccak256(bytes(name));
bytes32 versionHash =
_domainNameAndVersionMayChange() ? bytes32(0) : keccak256(bytes(version));
_cachedNameHash = nameHash;
_cachedVersionHash = versionHash;
bytes32 separator;
if (!_domainNameAndVersionMayChange()) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
separator := keccak256(m, 0xa0)
}
}
_cachedDomainSeparator = separator;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* FUNCTIONS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Please override this function to return the domain name and version.
/// ```
/// function _domainNameAndVersion()
/// internal
/// pure
/// virtual
/// returns (string memory name, string memory version)
/// {
/// name = "Solady";
/// version = "1";
/// }
/// ```
///
/// Note: If the returned result may change after the contract has been deployed,
/// you must override `_domainNameAndVersionMayChange()` to return true.
function _domainNameAndVersion()
internal
view
virtual
returns (string memory name, string memory version);
/// @dev Returns if `_domainNameAndVersion()` may change
/// after the contract has been deployed (i.e. after the constructor).
/// Default: false.
function _domainNameAndVersionMayChange() internal pure virtual returns (bool result) {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the EIP-712 domain separator.
function _domainSeparator() internal view virtual returns (bytes32 separator) {
if (_domainNameAndVersionMayChange()) {
separator = _buildDomainSeparator();
} else {
separator = _cachedDomainSeparator;
if (_cachedDomainSeparatorInvalidated()) separator = _buildDomainSeparator();
}
}
/// @dev Returns the hash of the fully encoded EIP-712 message for this domain,
/// given `structHash`, as defined in
/// https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct.
///
/// The hash can be used together with {ECDSA-recover} to obtain the signer of a message:
/// ```
/// bytes32 digest = _hashTypedData(keccak256(abi.encode(
/// keccak256("Mail(address to,string contents)"),
/// mailTo,
/// keccak256(bytes(mailContents))
/// )));
/// address signer = ECDSA.recover(digest, signature);
/// ```
function _hashTypedData(bytes32 structHash) internal view virtual returns (bytes32 digest) {
// We will use `digest` to store the domain separator to save a bit of gas.
if (_domainNameAndVersionMayChange()) {
digest = _buildDomainSeparator();
} else {
digest = _cachedDomainSeparator;
if (_cachedDomainSeparatorInvalidated()) digest = _buildDomainSeparator();
}
/// @solidity memory-safe-assembly
assembly {
// Compute the digest.
mstore(0x00, 0x1901000000000000) // Store "\x19\x01".
mstore(0x1a, digest) // Store the domain separator.
mstore(0x3a, structHash) // Store the struct hash.
digest := keccak256(0x18, 0x42)
// Restore the part of the free memory slot that was overwritten.
mstore(0x3a, 0)
}
}
/// @dev Variant of `_hashTypedData` that excludes the chain ID.
/// Included for the niche use case of cross-chain workflows.
function _hashTypedDataSansChainId(bytes32 structHash)
internal
view
virtual
returns (bytes32 digest)
{
(string memory name, string memory version) = _domainNameAndVersion();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(0x00, _DOMAIN_TYPEHASH_SANS_CHAIN_ID)
mstore(0x20, keccak256(add(name, 0x20), mload(name)))
mstore(0x40, keccak256(add(version, 0x20), mload(version)))
mstore(0x60, address())
// Compute the digest.
mstore(0x20, keccak256(0x00, 0x80)) // Store the domain separator.
mstore(0x00, 0x1901) // Store "\x19\x01".
mstore(0x40, structHash) // Store the struct hash.
digest := keccak256(0x1e, 0x42)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Variant of `_hashTypedData` that excludes the chain ID and verifying contract.
/// Included for the niche use case of cross-chain and multi-verifier workflows.
function _hashTypedDataSansChainIdAndVerifyingContract(bytes32 structHash)
internal
view
virtual
returns (bytes32 digest)
{
(string memory name, string memory version) = _domainNameAndVersion();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(0x00, _DOMAIN_TYPEHASH_SANS_CHAIN_ID_AND_VERIFYING_CONTRACT)
mstore(0x20, keccak256(add(name, 0x20), mload(name)))
mstore(0x40, keccak256(add(version, 0x20), mload(version)))
// Compute the digest.
mstore(0x20, keccak256(0x00, 0x60)) // Store the domain separator.
mstore(0x00, 0x1901) // Store "\x19\x01".
mstore(0x40, structHash) // Store the struct hash.
digest := keccak256(0x1e, 0x42)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/// @dev Variant of `_hashTypedData` that excludes the chain ID and verifying contract.
/// Included for the niche use case of multi-verifier workflows.
function _hashTypedDataSansVerifyingContract(bytes32 structHash)
internal
view
virtual
returns (bytes32 digest)
{
(string memory name, string memory version) = _domainNameAndVersion();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(0x00, _DOMAIN_TYPEHASH_SANS_VERIFYING_CONTRACT)
mstore(0x20, keccak256(add(name, 0x20), mload(name)))
mstore(0x40, keccak256(add(version, 0x20), mload(version)))
mstore(0x60, chainid())
// Compute the digest.
mstore(0x20, keccak256(0x00, 0x80)) // Store the domain separator.
mstore(0x00, 0x1901) // Store "\x19\x01".
mstore(0x40, structHash) // Store the struct hash.
digest := keccak256(0x1e, 0x42)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-5267 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev See: https://eips.ethereum.org/EIPS/eip-5267
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
fields = hex"0f"; // `0b01111`.
(name, version) = _domainNameAndVersion();
chainId = block.chainid;
verifyingContract = address(this);
salt = salt; // `bytes32(0)`.
extensions = extensions; // `new uint256[](0)`.
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the EIP-712 domain separator.
function _buildDomainSeparator() private view returns (bytes32 separator) {
// We will use `separator` to store the name hash to save a bit of gas.
bytes32 versionHash;
if (_domainNameAndVersionMayChange()) {
(string memory name, string memory version) = _domainNameAndVersion();
separator = keccak256(bytes(name));
versionHash = keccak256(bytes(version));
} else {
separator = _cachedNameHash;
versionHash = _cachedVersionHash;
}
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), separator) // Name hash.
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
separator := keccak256(m, 0xa0)
}
}
/// @dev Returns if the cached domain separator has been invalidated.
function _cachedDomainSeparatorInvalidated() private view returns (bool result) {
uint256 cachedChainId = _cachedChainId;
uint256 cachedThis = _cachedThis;
/// @solidity memory-safe-assembly
assembly {
result := iszero(and(eq(chainid(), cachedChainId), eq(address(), cachedThis)))
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"solady/=../operations/lib/solady/src/",
"forge-std/=../operations/lib/forge-std/src/",
"seadrop/=../operations/lib/seadrop/src/",
"ERC721A/=../operations/lib/seadrop/lib/ERC721A/contracts/",
"openzeppelin-contracts/=../operations/lib/seadrop/lib/openzeppelin-contracts/contracts/",
"operator-filter-registry/=../operations/lib/seadrop/lib/operator-filter-registry/src/",
"solmate/=../operations/lib/seadrop/lib/solmate/src/",
"utility-contracts/=../operations/lib/seadrop/lib/utility-contracts/src/",
"ERC721A-Upgradeable/=/Users/fredarnal/Desktop/Code/scripts-library/solidity/operations/lib/seadrop/lib/ERC721A-Upgradeable/contracts/",
"create2-helpers/=/Users/fredarnal/Desktop/Code/scripts-library/solidity/operations/lib/seadrop/lib/create2-helpers/",
"create2-scripts/=/Users/fredarnal/Desktop/Code/scripts-library/solidity/operations/lib/seadrop/lib/create2-helpers/script/",
"ds-test/=/Users/fredarnal/Desktop/Code/scripts-library/solidity/operations/lib/seadrop/lib/ds-test/src/",
"murky/=/Users/fredarnal/Desktop/Code/scripts-library/solidity/operations/lib/seadrop/lib/murky/src/",
"openzeppelin-contracts-upgradeable/=/Users/fredarnal/Desktop/Code/scripts-library/solidity/operations/lib/seadrop/lib/openzeppelin-contracts-upgradeable/contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.