Verified contractPartialMIT
QuantumNotes
Address0xbc4628e522dc5cd588a513fb68b087cbee434f4d
- Balance
0 ETH
- Transactions
6
- Compiler
solc 0.8.26
- Same code
1 more contract
Details
- Compiler
- solc 0.8.26+commit.8a97fa7a
- Language
- solidity
- Optimization
- Yes, 800 runs
- EVM version
- cancun
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,242,321
- Creation transaction
- 0x80c88479a0…9d28d0ecf9
6 files
- src/QuantumNotes.solmain17.68 KB
- lib/openzeppelin-contracts/contracts/access/Ownable.sol3.1 KB
- lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol2.48 KB
- lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol2.06 KB
- lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol5.07 KB
src/QuantumNotes.sol
// SPDX-License-Identifier: MIT
// Web: TBD
// X: TBD
pragma solidity 0.8.26;
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
interface IPoseidon1 {
function poseidon(uint256[1] calldata) external pure returns (uint256);
}
interface IPoseidon2 {
function poseidon(uint256[2] calldata) external pure returns (uint256);
}
interface IGroth16Verifier {
function verifyProof(
uint256[2] calldata a,
uint256[2][2] calldata b,
uint256[2] calldata c,
uint256[3] calldata pub
) external view returns (bool);
}
/// @title QuantumNotes
/// @notice Private launch notes. A user deposits exactly 0.1, 0.2 or 0.5 ETH with a commitment
/// Poseidon(nullifier, secret). Later, a zero-knowledge proof that they own SOME note of that tier is
/// enough for the pad to launch a token with it; which deposit (and so which wallet) paid is never revealed.
///
/// - One Merkle tree per tier, so every note in a tree is identical (same amount = same anonymity set).
/// - A note can only be spent by the pad (`spend`), and only once (nullifier).
/// - A note that was never used can be refunded, but ONLY to the wallet that deposited it (`refund`).
/// - A note spent on a PARTIAL launch (dev buy < 100%) leaves a `remainder`, claimable back to the
/// original depositor with `claimRemainder`. Both paths return ETH to its source, never to a fresh
/// wallet, so the contract is not a mixer: ETH only becomes a token launch or goes back where it came.
/// - CUSTODIAL EMERGENCY: the owner (dev) can withdraw funds at any time, WITHOUT shutting the contract
/// down -- `devWithdraw(amount, to)` for a targeted refund, `ESNotes()` to pull everything. This is a
/// deliberate safety lever for doing refunds if something fails; it makes the contract FULLY custodial
/// (the owner is trusted not to under-collateralize live notes). Depositors trust the owner with this.
contract QuantumNotes is ReentrancyGuardTransient, Ownable2Step {
/// @notice BN254 scalar field (the circuit's field, `r` in the verifier).
uint256 public constant FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint32 public constant LEVELS = 20;
/// @dev Proofs stay valid for the last 100 roots, so a burst of deposits does not void pending launches.
uint32 public constant ROOT_HISTORY = 100;
uint8 public constant TIERS = 5;
IPoseidon1 public immutable POSEIDON1;
IPoseidon2 public immutable POSEIDON2;
IGroth16Verifier public immutable VERIFIER;
/// @notice The only contract allowed to spend notes (the Quantum Pad hook). Set once.
address public pad;
/// @notice When true: no new deposits and no new launches (spend). Exits (refund, claimRemainder) and the
/// dev rescues stay open, so a pause never traps anyone's funds. Reversible.
bool public paused;
/// @notice Migration import window. A freshly deployed QuantumNotes (same source) can rebuild the old
/// contract's exact trees/state from public data while this is open, then latch it shut forever.
bool public migrationOpen;
bool public migrationClosed;
/// @notice Block of deployment: clients rebuild the trees from Deposit events starting here.
uint256 public immutable DEPLOY_BLOCK;
struct Tree {
uint32 nextIndex;
uint32 currentRootIndex;
uint256[LEVELS] filledSubtrees;
uint256[ROOT_HISTORY] roots;
}
/// @dev Zero value of an empty subtree at each level: zeros[0] = 0, zeros[i+1] = H(zeros[i], zeros[i]).
uint256[LEVELS + 1] public zeros;
Tree[TIERS] internal trees;
mapping(uint256 commitment => address depositor) public depositorOf;
mapping(uint256 nullifierHash => bool) public nullifierSpent;
/// @dev Tier of each leaf, plus one (0 = not a leaf). Lets `refund` pay the right denomination.
mapping(uint256 commitment => uint8 tierPlusOne) internal leafTier;
/// @notice Leftover ETH of a partial launch, keyed by the launch's nullifierHash. Claimable to the depositor.
mapping(uint256 nullifierHash => uint256) public remainder;
event Deposit(uint8 indexed tier, uint256 indexed commitment, uint32 leafIndex, uint256 timestamp);
event Spent(uint8 indexed tier, uint256 indexed nullifierHash);
event Refunded(uint8 indexed tier, uint256 indexed commitment, address indexed to);
event PadSet(address pad);
event EmergencySwept(address indexed to, uint256 amount);
event RemainderStored(uint256 indexed nullifierHash, uint256 amount);
event RemainderClaimed(uint256 indexed nullifierHash, address indexed to, uint256 amount);
event DevWithdraw(address indexed to, uint256 amount);
event PausedSet(bool paused);
event MigrationOpened();
event MigrationClosed();
event MigratedDeposit(uint8 indexed tier, uint256 indexed commitment, uint32 leafIndex);
error BadTier();
error WrongAmount();
error BadCommitment();
error DuplicateCommitment();
error TreeFull();
error NotPad();
error PadAlreadySet();
error UnknownRoot();
error NoteAlreadySpent();
error InvalidProof();
error NotDepositor();
error TransferFailed();
error ReleaseAboveDeposit();
error NothingToClaim();
error ZeroAddress();
error IsPaused();
error MigrationNotOpen();
error MigrationAlreadyUsed();
error TreesNotEmpty();
error LengthMismatch();
error MigrationInProgress();
constructor(IPoseidon1 p1, IPoseidon2 p2, IGroth16Verifier verifier, address owner_) Ownable(owner_) {
POSEIDON1 = p1;
POSEIDON2 = p2;
VERIFIER = verifier;
DEPLOY_BLOCK = block.number;
uint256 z = 0;
for (uint32 i; i <= LEVELS; ++i) {
zeros[i] = z;
z = p2.poseidon([z, z]);
}
for (uint8 t; t < TIERS; ++t) {
Tree storage tr = trees[t];
for (uint32 i; i < LEVELS; ++i) {
tr.filledSubtrees[i] = zeros[i];
}
tr.roots[0] = zeros[LEVELS];
}
}
/// @notice One-time wiring to the pad. Only the owner, only once.
/// @notice Security pause/resume. Blocks new deposits and new launches; exits and rescues stay open.
function setPaused(bool paused_) external onlyOwner {
paused = paused_;
emit PausedSet(paused_);
}
// ================================================================== migration import (dev only)
//
// Break-glass migration to a NEW QuantumNotes if the old one must be retired. All inputs are PUBLIC data
// from the old contract (Deposit/Spent events, depositorOf, remainder), so this re-seeds the SAME trees
// (same per-tier order => same Merkle roots) and the SAME spent/remainder state. Users keep their notes and
// their proofs keep verifying, as long as Poseidon and the verifier are unchanged. The dev funds the new
// contract with the backing ETH via `fundMigration`. Pools/launches can NOT be migrated (a v4 pool is bound
// to its hook address); those stay on the old hook.
/// @notice Open the import window. Only on a fresh contract (empty trees), only once (never after close).
function openMigration() external onlyOwner {
if (migrationClosed) revert MigrationAlreadyUsed();
for (uint8 t; t < TIERS; ++t) {
if (trees[t].nextIndex != 0) revert TreesNotEmpty();
}
migrationOpen = true;
emit MigrationOpened();
}
/// @notice Re-insert deposits in the SAME per-tier order as the old contract (read from its Deposit events).
function migrateDeposits(uint8[] calldata tiers, uint256[] calldata commitments, address[] calldata depositors)
external
onlyOwner
{
if (!migrationOpen) revert MigrationNotOpen();
if (tiers.length != commitments.length || tiers.length != depositors.length) revert LengthMismatch();
for (uint256 i; i < tiers.length; ++i) {
uint256 commitment = commitments[i];
if (commitment == 0 || commitment >= FIELD_SIZE) revert BadCommitment();
if (depositorOf[commitment] != address(0)) revert DuplicateCommitment();
depositorOf[commitment] = depositors[i];
uint32 index = _insert(tiers[i], commitment);
emit MigratedDeposit(tiers[i], commitment, index);
}
}
/// @notice Mark the nullifiers already spent on the old contract (from its Spent events), so a migrated note
/// that already launched/refunded can not be used again here.
function migrateSpent(uint256[] calldata nullifierHashes) external onlyOwner {
if (!migrationOpen) revert MigrationNotOpen();
for (uint256 i; i < nullifierHashes.length; ++i) {
nullifierSpent[nullifierHashes[i]] = true;
}
}
/// @notice Restore pending remainders (from the old contract's `remainder`), claimable by the same depositors.
function migrateRemainder(uint256[] calldata nullifierHashes, uint256[] calldata amounts) external onlyOwner {
if (!migrationOpen) revert MigrationNotOpen();
if (nullifierHashes.length != amounts.length) revert LengthMismatch();
for (uint256 i; i < nullifierHashes.length; ++i) {
remainder[nullifierHashes[i]] = amounts[i];
}
}
/// @notice Fund the new contract with the backing ETH (what the old contract held) so refunds/claims work.
function fundMigration() external payable onlyOwner {}
/// @notice Close the import window for good and open the contract for normal use.
function finalizeMigration() external onlyOwner {
migrationOpen = false;
migrationClosed = true;
emit MigrationClosed();
}
function setPad(address pad_) external onlyOwner {
if (pad != address(0)) revert PadAlreadySet();
if (pad_ == address(0)) revert NotPad();
pad = pad_;
emit PadSet(pad_);
}
function denomination(uint8 tier) public pure returns (uint256) {
if (tier == 0) return 0.1 ether;
if (tier == 1) return 0.2 ether;
if (tier == 2) return 0.3 ether;
if (tier == 3) return 0.5 ether;
if (tier == 4) return 1 ether;
revert BadTier();
}
// ================================================================== deposit
function deposit(uint8 tier, uint256 commitment) external payable nonReentrant {
if (paused || migrationOpen) revert IsPaused();
if (msg.value != denomination(tier)) revert WrongAmount();
if (commitment == 0 || commitment >= FIELD_SIZE) revert BadCommitment();
if (depositorOf[commitment] != address(0)) revert DuplicateCommitment();
depositorOf[commitment] = msg.sender;
uint32 index = _insert(tier, commitment);
emit Deposit(tier, commitment, index, block.timestamp);
}
// ================================================================== spend (pad only)
/// @notice Verifies the proof, burns the nullifier, sends `release` ETH to the pad and keeps the rest as a
/// claimable remainder for the depositor. `release` is what the pad needs (platform fee + relayer fee
/// + the dev buy); the pad computes it from the note's buyBps. `release <= denomination(tier)`.
function spend(
uint8 tier,
uint256[2] calldata a,
uint256[2][2] calldata b,
uint256[2] calldata c,
uint256 root,
uint256 nullifierHash,
uint256 extDataHash,
uint256 release
) external nonReentrant returns (uint256 released) {
if (msg.sender != pad) revert NotPad();
if (paused) revert IsPaused();
if (migrationOpen) revert MigrationInProgress();
uint256 denom = denomination(tier);
if (release > denom) revert ReleaseAboveDeposit();
if (nullifierSpent[nullifierHash]) revert NoteAlreadySpent();
if (!isKnownRoot(tier, root)) revert UnknownRoot();
if (!VERIFIER.verifyProof(a, b, c, [root, nullifierHash, extDataHash])) revert InvalidProof();
nullifierSpent[nullifierHash] = true;
uint256 rest = denom - release;
if (rest != 0) {
remainder[nullifierHash] = rest;
emit RemainderStored(nullifierHash, rest);
}
emit Spent(tier, nullifierHash);
released = release;
if (release != 0) _send(msg.sender, release);
}
// ================================================================== refund (depositor only)
/// @notice Gets an unused note's ETH back, only to the wallet that deposited it. Reveals the note, so it
/// is for notes that will never launch.
function refund(uint8 tier, uint256 nullifier, uint256 secret) external nonReentrant {
if (migrationOpen) revert MigrationInProgress();
uint256 commitment = POSEIDON2.poseidon([nullifier, secret]);
if (depositorOf[commitment] != msg.sender) revert NotDepositor();
uint256 nullifierHash = POSEIDON1.poseidon([nullifier]);
if (nullifierSpent[nullifierHash]) revert NoteAlreadySpent();
if (!_leafInTier(tier, commitment)) revert BadTier();
nullifierSpent[nullifierHash] = true;
emit Refunded(tier, commitment, msg.sender);
_send(msg.sender, denomination(tier));
}
// ================================================================== remainder (funder) / custodial (dev)
/// @notice Claims the leftover ETH of a PARTIAL launch back to the wallet that deposited the note. Anyone can
/// trigger it; the ETH always goes to the original depositor (return-to-source, never a fresh wallet).
function claimRemainder(uint256 nullifier, uint256 secret) external nonReentrant {
if (migrationOpen) revert MigrationInProgress();
uint256 commitment = POSEIDON2.poseidon([nullifier, secret]);
address dep = depositorOf[commitment];
if (dep == address(0)) revert NotDepositor();
uint256 nullifierHash = POSEIDON1.poseidon([nullifier]);
uint256 amount = remainder[nullifierHash];
if (amount == 0) revert NothingToClaim();
remainder[nullifierHash] = 0;
emit RemainderClaimed(nullifierHash, dep, amount);
_send(dep, amount);
}
/// @notice CUSTODIAL: the dev withdraws a specific amount to any address (e.g. to refund a note that failed),
/// without shutting the contract down. Fully trusts the owner not to under-collateralize live notes.
function devWithdraw(uint256 amount, address to) external onlyOwner nonReentrant {
if (to == address(0)) revert ZeroAddress();
emit DevWithdraw(to, amount);
_send(to, amount);
}
/// @notice CUSTODIAL: the dev pulls ALL the ETH to itself, without shutting the contract down.
function ESNotes() external onlyOwner nonReentrant {
uint256 amount = address(this).balance;
emit EmergencySwept(owner(), amount);
if (amount != 0) _send(owner(), amount);
}
// ================================================================== views
function isKnownRoot(uint8 tier, uint256 root) public view returns (bool) {
if (tier >= TIERS) revert BadTier();
if (root == 0) return false;
Tree storage tr = trees[tier];
uint32 i = tr.currentRootIndex;
do {
if (tr.roots[i] == root) return true;
i = i == 0 ? ROOT_HISTORY - 1 : i - 1;
} while (i != tr.currentRootIndex);
return false;
}
function lastRoot(uint8 tier) external view returns (uint256) {
return trees[tier].roots[trees[tier].currentRootIndex];
}
function nextIndex(uint8 tier) external view returns (uint32) {
return trees[tier].nextIndex;
}
/// @notice How many notes of a tier exist (the anonymity set a launch hides in).
function depositCount(uint8 tier) external view returns (uint32) {
return trees[tier].nextIndex;
}
// ================================================================== internals
function _leafInTier(uint8 tier, uint256 commitment) internal view returns (bool) {
return leafTier[commitment] == tier + 1;
}
function _insert(uint8 tier, uint256 leaf) internal returns (uint32 index) {
Tree storage tr = trees[tier];
index = tr.nextIndex;
if (index == uint32(1) << LEVELS) revert TreeFull();
leafTier[leaf] = tier + 1;
uint256 current = leaf;
uint32 idx = index;
for (uint32 i; i < LEVELS; ++i) {
uint256 left;
uint256 right;
if (idx % 2 == 0) {
left = current;
right = zeros[i];
tr.filledSubtrees[i] = current;
} else {
left = tr.filledSubtrees[i];
right = current;
}
current = POSEIDON2.poseidon([left, right]);
idx /= 2;
}
uint32 newRootIndex = (tr.currentRootIndex + 1) % ROOT_HISTORY;
tr.currentRootIndex = newRootIndex;
tr.roots[newRootIndex] = current;
tr.nextIndex = index + 1;
}
function _send(address to, uint256 amount) internal {
(bool ok,) = to.call{value: amount}("");
if (!ok) revert TransferFailed();
}
}
lib/openzeppelin-contracts/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This extension of the {Ownable} contract includes a two-step mechanism to transfer
* ownership, where the new owner must call {acceptOwnership} in order to replace the
* old one. This can help prevent common mistakes, such as transfers of ownership to
* incorrect accounts, or to contracts that are unable to interact with the
* permission system.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*
* Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuardTransient.sol)
pragma solidity ^0.8.24;
import {TransientSlot} from "./TransientSlot.sol";
/**
* @dev Variant of {ReentrancyGuard} that uses transient storage.
*
* NOTE: This variant only works on networks where EIP-1153 is available.
*
* _Available since v5.1._
*/
abstract contract ReentrancyGuardTransient {
using TransientSlot for *;
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant REENTRANCY_GUARD_STORAGE =
0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_reentrancyGuardEntered()) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
}
function _nonReentrantAfter() private {
REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
}
}
lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.
pragma solidity ^0.8.24;
/**
* @dev Library for reading and writing value-types to specific transient storage slots.
*
* Transient slots are often used to store temporary values that are removed after the current transaction.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* * Example reading and writing values using transient storage:
* ```solidity
* contract Lock {
* using TransientSlot for *;
*
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
*
* modifier locked() {
* require(!_LOCK_SLOT.asBoolean().tload());
*
* _LOCK_SLOT.asBoolean().tstore(true);
* _;
* _LOCK_SLOT.asBoolean().tstore(false);
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library TransientSlot {
/**
* @dev UDVT that represent a slot holding a address.
*/
type AddressSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a AddressSlot.
*/
function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
return AddressSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bool.
*/
type BooleanSlot is bytes32;
/**
* @dev Cast an arbitrary slot to a BooleanSlot.
*/
function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
return BooleanSlot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a bytes32.
*/
type Bytes32Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Bytes32Slot.
*/
function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
return Bytes32Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a uint256.
*/
type Uint256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Uint256Slot.
*/
function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
return Uint256Slot.wrap(slot);
}
/**
* @dev UDVT that represent a slot holding a int256.
*/
type Int256Slot is bytes32;
/**
* @dev Cast an arbitrary slot to a Int256Slot.
*/
function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
return Int256Slot.wrap(slot);
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(AddressSlot slot) internal view returns (address value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(AddressSlot slot, address value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(BooleanSlot slot) internal view returns (bool value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(BooleanSlot slot, bool value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Bytes32Slot slot, bytes32 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Uint256Slot slot) internal view returns (uint256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Uint256Slot slot, uint256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
/**
* @dev Load the value held at location `slot` in transient storage.
*/
function tload(Int256Slot slot) internal view returns (int256 value) {
assembly ("memory-safe") {
value := tload(slot)
}
}
/**
* @dev Store `value` at location `slot` in transient storage.
*/
function tstore(Int256Slot slot, int256 value) internal {
assembly ("memory-safe") {
tstore(slot, value)
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 800,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"forge-std/=lib/forge-std/src/",
"ds-test/=lib/forge-std/lib/ds-test/src/",
"@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
"@uniswap/v4-periphery/=lib/v4-periphery/",
"solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
"permit2/=lib/v4-periphery/lib/permit2/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
"lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"lib/openzeppelin-contracts/:erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"@ensdomains/=lib/v4-periphery/lib/v4-core/node_modules/@ensdomains/",
"@openzeppelin/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"hardhat/=lib/v4-periphery/lib/v4-core/node_modules/hardhat/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"v4-core/=lib/v4-periphery/lib/v4-core/src/",
"v4-periphery/=lib/v4-periphery/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.